World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Explain 2d Arrays in Python, with Examples
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) # Output: 1 print(arr) # Output: 7 print(arr) # 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 accesses the element in the first row and first column, which is
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.
Running random forest algorithm with one variable