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 Python program to create a nested list and display its elements.


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:



But we want to retrieve columns (or elements) in each row; hence we need another for loop inside the previous loop, as:


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: