Working with Nested Lists in Python (5 Examples)

Updated: June 12, 2023 By: Frienzied Flame Post a comment

In Python, nested lists are lists that contain other lists as their elements. They can be useful for storing and manipulating complex data structures, such as matrices, graphs, or trees.

Creating Nested Lists

In order to create a nested list, you can simply use square brackets [] to enclose one or more lists inside another list.

Example:

nested_list = [[1, 2, 3], ["a", "b", "c"], [True, False, None]]
print(nested_list)

Output:

[[1, 2, 3], ['a', 'b', 'c'], [True, False, None]]

Sometimes, list comprehension can also be used to construct a nested list:

from pprint import pprint

# Creating a 3x3x3 nested list of zeros using list comprehension
nested_list = [[[0 for i in range(3)] for j in range(3)] for k in range(3)]

# Printing the nested list in a pretty way
pprint(nested_list)

Output:

[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

The pprint() function from the pprint module helps us print big nested lists in a beautiful manner.

Accessing and Modifying Elements in a Nested List

When it comes to accessing or modifying the elements of a nested list, you can use two indices: the first one specifies the sublist, and the second one specifies the element within that sublist. The indices start from zero and can be positive or negative.

Example:

nested_list = [[1, 2, 3], ["a", "b", "c"], [True, False, None]]

# Accessing the first element of the first sublist
print(nested_list[0][0]) 
# Output: 1

# Accessing the last element of the last sublist
print(nested_list[-1][-1]) 
# Output: None

# Modifying the second element of the second sublist
nested_list[1][1] = "x"
print(nested_list) 
# Output: [[1, 2, 3], ["a", "x", "c"], [True, False, None]]

Iterating Over a Nested List

The way to iterate over the elements of a nested list is to use nested for loops. The outer loop iterates over the sublists and the inner loop iterates over the elements within each sublist.

Example:

nested_list = [[1, 2, 3], ["a", "b", "c"], [True, False, None]]

# Printing all the elements of a nested list
for sublist in nested_list:
    for element in sublist:
        print(element)

Output:

1
2
3
a
b
c
True
False
None

In case you want to get both the indices and the elements of a nested list, the enumerate() function is the right choice.

Example:

nested_list = [
    ['puppy', 'kitty', 'petey'],
    [2023, 2024, 2025],
    [True, False]
]

# Printing the indices and the elements of a nested list
for i, sublist in enumerate(nested_list):
    for j, element in enumerate(sublist):
        print(f"nested_list[{i}][{j}] = {element}")

Output:

ested_list[0][0] = puppy
nested_list[0][1] = kitty
nested_list[0][2] = petey
nested_list[1][0] = 2023
nested_list[1][1] = 2024
nested_list[1][2] = 2025
nested_list[2][0] = True
nested_list[2][1] = False

That’s it. Happy coding!