Sling Academy
Home/Python/Working with Nested Lists in Python (5 Examples)

Working with Nested Lists in Python (5 Examples)

Last updated: June 12, 2023

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!

Next Article: Python: How to Flatten a Nested List (3 Approaches)

Previous Article: Sorting Lists in Python (4 Examples)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots