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) function 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:

example image for indexing multi dimensional arrays

A Python program to retrieve the elements from a 2D array and display them using for loops.


A Python program to retrieve the elements from a 3D array.