What are nested lists in Python?

Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if we want to create a matrix or need to store a sublist along with other data types.

An example of a nested list

Here is how you would create the example nested list above:

# creating list
nestedList = [1, 2, ['a', 1], 3]
# indexing list: the sublist has now been accessed
subList = nestedList[2]
# access the first element inside the inner list:
element = nestedList[2][0]
print("List inside the nested list: ", subList)
print("First element of the sublist: ", element)

Creating a matrix

Creating a matrix is one of the most useful applications of nested lists. This is done by creating a nested list that only has other lists of equal length as elements.

The number of elements in the nested lists is equal to the number of rows of the matrix.

The length of the lists inside the nested list is equal to the number of columns.

Thus, each element of the nested list (matrix) will have two indices: the row and the column.

A matrix of size 3x3
# create matrix of size 4 x 3
matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]]
rows = len(matrix) # no of rows is no of sublists i.e. len of list
cols = len(matrix[0]) # no of cols is len of sublist
# printing matrix
print("matrix: ")
for i in range(0, rows):
print(matrix[i])
# accessing the element on row 2 and column 1 i.e. 3
print("element on row 2 and column 1: ", matrix[1][0])
# accessing the element on row 3 and column 2 i.e. 7
print("element on row 3 and column 2: ", matrix[2][1])

Free Resources