Nested Lists in Python can be best defined as a ‘list within another list’. A Python list can have elements of different type, when we take a list as an element of the main list, then that list is called a nested list.
Consider two lists, l1, l2
l1 = [1, 2, 3, 4]
l2 = [5, l1]
In the above code, we have added l1 as an element of list l2, hence, l1 is our nested list.
l1 = [1, 2, 3, 4]
l2 = [5, l1]
print(l2)
O/P
[5, [1, 2, 3, 4]]
Hence,
l[0] = 5
l2[1] = [1, 2, 3, 4]
So, l2[3] is our nested list. To print of the elements, we can use for loop, like
for i in l2[1]:
print(i, end= ' ')
O/P
1 2 3 4
Similarly,
l2[1][0] = 1
l2[1][1] = 2
l2[1][2] = 3
l2[1][3] = 4
Representing Lists as Matrices
A matrix is a two-dimensional data structure where numbers are arranged into rows and columns.
For example, a matrix with two rows and two columns will look like

In Python, we can represent this matrix with Nested Lists. For example, above matrix can be represented as
mat = [[2, 3], [1, 4]]
Similarly, matrix for 3 by 3 will look like :
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Here, [1, 2, 3] is the first row. Let’s try to access this matrix or Nested Lists.
mat = [[2, 3], [1, 4]]
for i in mat: # loop row by row
print(i)
O/P
[2, 3]
[1, 4]
Now, lets try to retrieve columns in each row
mat = [[2, 3], [1, 4]]
for i in mat: # loop row by row
for j in i: # loop column
print(j, end = ' ')
print()
O/P
2 3
1 4
Another way of traversing nested list
mat = [[2, 3], [1, 4]]
for i in range(len(mat)): # loop row by row
for j in range(len(mat[i])): # loop column
print(mat[i][j], end = ' ')
print()
O/P
2 3
1 4
That’s all here.
