All Courses

Explain concept of 2diamentional Arrays in Python, with Examples

By Pp5344229@gmail.com, 4 months ago
  • Bookmark
0

Explain 2d Arrays in Python, with Examples

Python
Arrays
2diamentional arrays
1 Answer
0
Goutamp777

In Python, a 2-dimensional array is a data structure that allows you to store elements in a grid or matrix-like structure, with rows and columns. It's essentially a list of lists, where each sub-list represents a row of the matrix. You can think of it as a table with rows and columns.

Here's an example of how to create a 2-dimensional array in Python:

# Create a 2D array with 3 rows and 4 columns
arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]


# Accessing the elements of the 2D array
print(arr[0][0])  # Output: 1
print(arr[1][2])  # Output: 7
print(arr[2][3])  # Output: 12


In the above example, arr is a 2-dimensional array with 3 rows and 4 columns. The first row is [1, 2, 3, 4], the second row is [5, 6, 7, 8], and the third row is [9, 10, 11, 12].

To access an element in the 2D array, you need to use two indexes. The first index corresponds to the row number, and the second index corresponds to the column number. So arr[0][0] accesses the element in the first row and first column, which is 1.

You can also loop through a 2D array using nested loops:


# Looping through the 2D array
for i in range(len(arr)):
    for j in range(len(arr[i])):
        print(arr[i][j], end=" ")
    print()


This will output the elements of the 2D array in row-major order:

1 2 3 4 
5 6 7 8 
9 10 11 12 

Overall, 2D arrays are a useful way to store and manipulate data in a matrix-like structure.

Your Answer

Webinars

Why You Should Learn Data Science in 2023?

Jun 8th (7:00 PM) 289 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More