Python Nested Lists
A list within another list is called a nested list. When we take a list as an element in another list, then that list is called a nested list. For example, we have two lists 'a' and 'b' as:
a = [80, 90]
b = [10, 20, 30, a]
Observe that the list 'a' is inserted as an element in the list 'b' and hence 'a' is called a nested list.
Let's display the elements of 'b', by writing the following statement:
print(b)
The elements of b appears:
[10, 20, 30, [80, 90]]
The last element [80, 90] represents a nested list. So, 'b' has 4 elements and they are:
b[0] = 10
b[1] = 20
b[2] = 30
b[3] = [80, 90]
So, b[3] represents the nested list and if we want to display its elements separately, we can use a for loop as:
for x in b[3]:
print(x)
A Python program to create a nested list and display its elements.
#To create a list with another list as element
list = [10, 20, 30, [80, 90]]
print('Total list=', list) #display entire list
print('First element=', list[0]) #display first element
print('Last element is nested list=', list[3]) #display nested list
for x in list[3]: #display all elements in nested list
print(x)
Nested Lists as Matrices
Suppose we want to create a matrix with 3 rows and 3 columns, we should create a list with 3 other lists as:
mat = [[1,2,3], [4,5,6], [7,8,9]]
Here, 'mat' is a list that contains 3 lists which are rows of the 'mat' list. Each row contains again 3 elements as:
[[1,2,3], #first row
[4,5,6], #second row
[7,8,9]] #third row
If we use a for loop to retrieve the elements from 'mat', it will retrieve row by row, as:
for r in mat:
print(r) #display row by row
But we want to retrieve columns (or elements) in each row; hence we need another for loop inside the previous loop, as:
for r in mat:
for c in r: #display columns in each row
print(c, end='')
print()
Another way to display the elements of a matrix is using indexing. For example, mat[i][j] represents the ith row and jth column element. Suppose the matrix has 'm' rows and 'n' columns, we can retrieve the elements as:
for i in range(len(mat)): #i values change from 0 to m-1
for j in range(len(mat[i])): #j values change from 0 to n-1
print('%d ' %mat[i][j], end='')
print()