Python Indexing Multi-dimensional Arrays
Index represents the location number. The individual elements of a 2D array can be accessed by specifying the location number of the row and column of the element in the array as:
a[0][0] #represents 0th row and 0th column element in the array 'a'
b[1][3] #represents 1st row and 3rd column element in the array 'b'
Suppose 'a' is the array name. len(a) fun ction will give the number of rows in the array . a[0] represents the 0th row, a[1] represents the 1st row, etc. So, in general, a[i] represents the ith row elements. Hence, to display only rows of the 2D array, we can write:
for i in range(len(a)):
print(a[i])
Each row may contain some columns which represent the elements. To know, how many elements are there in a row, we can use len(a[i]) . Here, if i = 0, then len(a[0]) represents the number of columns in 0th row. Similarly if i=1, then len(a[1]) represents the number of columns in 1st row and so on. In this way, len(a[i]) represents the number of columns in ith row. So, the following loops will access all elements from the 2D array:
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=' ')
print()
A Python program to retrieve the elements from a 2D array and display them using for loops.
from numpy import *
a = array([[1,2,3], [4,5,6], [7,8,9]])
for i in range(len(a)):
print(a[i])
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end='')
A Python program to retrieve the elements from a 3D array.
from numpy import *
a = array([[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]])
for i in range(len(a)):
for j in range(len(a[i])):
for k in range(len(a[i][j])):
print(a[i][j][k], end='\t')
print()
print()