Nested List in Python with Example

A nested list in Python is a simply list that contains a list as an element in another list. In simple words, a list inside another list is called nested list. It occurs as an element of another list.

Consider the below example code where the third element in the list is a nested list.

list = ["Hello", "Python", 5, [1, 2, 3, 4]]

When we access the third element as list[3] in the list, it will print [1, 2, 3, 4]. We often use nested lists for storing and accessing two-dimensional matrix data.

Syntax to create a Nested List in Python


The general syntax to create a nested list in Python is as:

nested_list_name = [[element1, element2, element3], 
                              [element4, element5, element6], 
                              [element7, element8, element9]]

In this syntax, nested_list_name is the name of a nested list in which there are present three lists of elements in the list. Each list is separated by a comma. The first bracket is opening bracket and the last bracket is closing bracket of the list.

Example 1:

# Python program to create and access elements of nested list.
# Creating a nested list of three elements.
nested_list = ["Python", 35, [1, 3, 5, 7]]

# Access elements of nested list one by one.
print("First element: ", nested_list[0])
print("Second element: ", nested_list[1])
print("Third element: ", nested_list[2])

# Accessing elements of sub-list inside a nested list.
print("\nFirst element of sub-list: ", nested_list[2][0])
print("Second element of sub-list: ", nested_list[2][1])
print("Third element of sub-list: ", nested_list[2][2])
print("Fourth element of sub-list: ", nested_list[2][3])
Output:
      First element:  Python
      Second element:  35
      Third element:  [1, 3, 5, 7]

      First element of sub-list:  1
      Second element of sub-list:  3
      Third element of sub-list:  5
      Fourth element of sub-list:  7

In this example, we have created a nested list having three elements, such as “Python”, 35, [1, 3, 5, 7]. The comma separates each element of the nested list.

Then, we have easily accessed each element one by one of the nested list by using index operator. For example, the first element is at location index 0 and the second element is at location index 1. Therefore, we can access them by nested_list[0] and nested_list[1], respectively.


Similarly, we have accessed elements of nested list. For example, we have accessed the first element of a nested list by nested_list[2][0], the second element by nested_list[2][1], and so on.

Example 2:

# Python program to create and access elements of nested list.
# Creating a nested list of three elements.
nested_list = [['India', 'USA'], ['England', 'Canada'], ['France']]

# Access elements of first sub-list one by one.
print("Elements of first sub-list: ")
print("First element: ", nested_list[0][0])
print("Second element: ", nested_list[0][1])

# Accessing elements of the second sub-list inside a nested list.
print("\nElements of second sub-list: ")
print("First element: ", nested_list[1][0])
print("Second element: ", nested_list[1][1])

# Accessing elements of the second sub-list inside a nested list.
print("\nElements of third sub-list: ")
print("First element: ", nested_list[2][0])

# Accessing the complete nested list.
print("\nComplete nested list: ")
print(nested_list)
Output:
       Elements of first sub-list: 
       First element:  India
       Second element:  USA

       Elements of second sub-list: 
       First element:  England
       Second element:  Canada

       Elements of third sub-list: 
       First element:  France
     
       Complete nested list: 
       [['India', 'USA'], ['England', 'Canada'], ['France']]

Matrices using Nested List in Python


In Python, we generally represent a matrix form with the help of nested lists. Look at the following example in the below figure.

Nested list in Python

From the above figure, a matrix is a list of three elements, each of which represents a row. We can select a complete row from the matrix by using the following syntax:

matrix[1] # Output: [4, 5, 6]

Similarly, we can use the double-index form to choose a single element from the matrix, like this:

matrix[1][1]

Let us take an example program in which we will print data row wise and in the matrix style of a given list.

Example 3:

# Creating a nested list of three elements.
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Displaying the whole nested list.
print("Whole nested list: ")
print(my_list)

# Displaying row data.
print("\nRow wise data: ")
for i in my_list:
    print(i)

# Displaying data in matrix style.
print("\nMatrix form: ")
for i in range(len(my_list)):
    for j in range(len(my_list[i])):
        print(my_list[i][j], end=" ")
    print()
Output:
       Whole nested list: 
       [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

       Row wise data: 
       [1, 2, 3]
       [4, 5, 6]
       [7, 8, 9]

       Matrix form: 
       1 2 3 
       4 5 6 
       7 8 9 

In this example, we have created a nested list of three elements as lists. Then, we have displayed the complete nested list on the console. Using for loop, we have printed elements in row wise.

Inside for loop, i represents row of the matrix. To print a matrix in Python, we have used two for loops corresponding to rows and columns of the matrix.

We have used variables i and j to represents row and column respectively. Then, we have iterated over each row and each column using for loop. At each iteration, we are printing my_list[i][j].


Let’s take an example program in which we will find the transpose of a matrix. It is a new matrix whose rows are the columns and columns are the rows of the original matrix.

Example 4:

# Creating a nested list of three elements.
matrix = [[1, 2],
              [3, 4],
              [5, 6]]
# Creating an empty matrix to store transposed matrix.
matrix_trans = [[0, 0, 0],
                      [0, 0, 0]]
# Creating a function named main.
def main():
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            matrix_trans[j][i] = matrix[i][j]
    print("Transposed matrix: ")
    for items in matrix_trans:
        print(items)
# Calling main() method.
main()
Output:
       Transposed matrix: 
       [1, 3, 5]
       [2, 4, 6]

In this example, we have created a matrix of three rows and two columns. To find the transpose of a matrix in Python, we have created an empty matrix of three columns and two rows to store the transposed matrix.

This empty matrix has one column greater and one row less than the original matrix. Then, we have created a function named main(). Inside main() method, we have used two for loops corresponding to rows and columns of the matrix.

We have used variables i and j to represents row and column respectively. Then, we have iterated over each row and each column using for loop. At each iteration, matrix_trans[j][i] is equal to matrix[i][j]. At last, we have displayed the elements of transposed matrix by using for loop.


Let’s take an example program in which we will determine the addition of two matrices.

Example 5:

# Creating two matrices of three elements.
matrix1 = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]]
matrix2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Creating an empty matrix to store the result of matrix.
matrix_result = [[0, 0, 0],
                        [0, 0, 0],
                        [0, 0, 0]]
# Creating a function named main.
def main():
    for i in range(len(matrix1)):
        for j in range(len(matrix2[0])):
            matrix_result[i][j] = matrix1[i][j] + matrix2[i][j]
    print("Addition of two matrices: ")
    for items in matrix_result:
        print(items)
# Calling main() method.
main()
Output:
      Addition of two matrices: 
      [2, 4, 6]
      [8, 10, 12]
      [14, 16, 18]

In this example, we have two matrices which has to be added. To add two matrices in Python, we have created an empty matrix named matrix_result to store the addition of two matrices.

To perform the addition of matrices, we have used two for loops corresponding to rows (i) and columns (j) of matrix1 and matrix2, respectively.

Then, we have iterated over each row and column of matrices using for loop. At each iteration, we have added elements of matrix1[i][j] with elements of matrix2[i][j]. At last, we have displayed the matrix result of adding two matrices using for loop.

Add Elements to Nested list


Python provides a built-in append() method to add a new element at the end of the nested list.

Example 6:

# Python program to add a new element at the end of nested list.
# Creating a nested list.
nested_list = [[1, 2], [3, 4]]
print("Nested list before adding: ")
print(nested_list)

# Calling append() method to add a new element at the end.
nested_list.append([5, 6])
print("Nested list after adding: ")
print(nested_list)
Output:
       Nested list before adding: 
       [[1, 2], [3, 4]]
       Nested list after adding: 
       [[1, 2], [3, 4], [5, 6]]

However, Python also provides a built-in method named insert() that we can use to add a new element at a specific position in the nested list.

Example 7:

# Python program to add a new element at a specific position in a nested list.
# Creating a nested list.
nested_list = [[1, 2], [3, 4]]
print("Nested list before adding: ")
print(nested_list)

# Calling insert() method to add a new element at a specific location.
nested_list[1].insert(1, 5)
print("Nested list after adding: ")
print(nested_list)
Output:
       Nested list before adding: 
       [[1, 2], [3, 4]]
       Nested list after adding: 
       [[1, 2], [3, 5, 4]]

We can merge one list into another by using extend() method provided by Python language.

Example 8:

# Python program to merge one list into another in a nested list.
# Creating a nested list.
nested_list = [[10, 20], [30, 40]]
print("Nested list before merging: ")
print(nested_list)

# Calling extend() method to merge a list into another list.
nested_list[1].extend([50, 60])
print("Nested list after merging: ")
print(nested_list)
Output:
       Nested list before merging: 
       [[10, 20], [30, 40]]
       Nested list after merging: 
       [[10, 20], [30, 40, 50, 60]]

Remove Elements from Nested List


Python provides a built-in remove() method to remove or delete an element by value from the nested list.

Example 9:

# Python program to remove an element by value from a nested list.
# Creating a nested list.
nested_list = [[10, 20], "Python", 25.5]
print("Nested list before removing: ")
print(nested_list)

# Calling remove() method to remove an element by value.
nested_list[0].remove(20)
print("Nested list after removing: ")
print(nested_list)
Output:
       Nested list before removing: 
       [[10, 20], 'Python', 25.5]
       Nested list after removing: 
       [[10], 'Python', 25.5]

If you know the index of the element you want, you can use pop() method provided by Python. This method modifies the list and returns the removed element.

Example 10:

# Python program to remove an element by index from a nested list.
# Creating a nested list.
nested_list = [[10, 20], "Python", 25.5]
print("Nested list before removing: ")
print(nested_list)

# Calling pop() method to remove an element by index.
removed_element = nested_list.pop(1)
print("Nested list after removing: ")
print(nested_list)

# Displaying the removed element.
print("Removed element: ", removed_element)
Output:
       Nested list before removing: 
       [[10, 20], 'Python', 25.5]
       Nested list after removing: 
       [[10, 20], 25.5]
       Removed element:  Python

Example 11:

# Python program to remove an element by del keyword from a nested list.
# Creating a nested list.
nested_list = [[5, 25], "Python", "Love"]
print("Nested list before removing: ")
print(nested_list)

# Removing an element by del keyword.
del nested_list[0][1]
print("Nested list after removing: ")
print(nested_list)
Output:
       Nested list before removing: 
       [[5, 25], 'Python', 'Love']
       Nested list after removing: 
       [[5], 'Python', 'Love']

Find Length of Nested List


We can use the built-in len() function provided by Python to find how many elements a nested sublist has.

Example 12:

# Python program to find the length of a nested list.
# Creating a nested list.
nested_list = [[5, 25, 50], "Python", "Love"]

print("Length of nested list: ", len(nested_list))
print("Length of sublist: ", len(nested_list[0]))
Output:
      Length of nested list:  3
      Length of sublist:  3

Iterate over a Nested List


To iterate over elements of a nested list, you can use simple for loop. Let’s take an example in which we will iterate over elements of a nested list in Python.

Example 13:

# Python program to iterate over elements of a nested list.
nested_list = [[5, 25, 50], "Python", [2, 4, 6, 8]]
for list in nested_list:
    for number in list:
        print(number, end= " ")
Output:
      5 25 50 P y t h o n 2 4 6 8 

In this tutorial, we have discussed a nested list in Python with the help of various examples. Hope that you will have understood the basic points of nested lists and practiced all example programs.
Thanks for reading!!!

Please share your love