Python Nested Lists: Creation, Access, and Modification
Learn how to create, access, iterate, and modify nested lists in Python, including flattening techniques and performance considerations.

A nested list in Python is a list that contains other lists as its elements. This structure is common when representing matrices, tables, or hierarchical data.
Creating Nested Lists
A nested list is created by placing lists inside another list literal, or by building it programmatically. The simplest form is:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]This creates a list of three lists. Each inner list is an independent object. You can also build nested lists with comprehensions:
grid = [[0 for _ in range(3)] for _ in range(3)]This produces a 3x3 grid where each row is a separate list. Note that using [[0] * 3] * 3 creates three references to the same list, which is a common mistake. The comprehension avoids that by creating a new list each iteration.
Accessing Elements
Accessing an element in a nested list requires two indices: one for the outer list and one for the inner list. For example:
matrix[0][1] # returns 2You can also use negative indices to access from the end. If the structure is deeper, add more indices. If you try to access an index that does not exist, Python raises an IndexError. Always verify the shape of your nested list when the data comes from user input or external sources.
Iterating Over Nested Lists
The natural way to iterate over a nested list is with nested for loops:
for row in matrix:
for value in row:
print(value)If you need the indices, use enumerate at each level. For a structure whose depth is unknown, a recursive function can traverse the list, but for typical two-dimensional data, nested loops are clearer and faster.
Modifying Nested Lists
Modification works at both levels. You can replace an entire row, or change a single element:
matrix[0] = [10, 11, 12] # replace first row
matrix[1][2] = 99 # change a single valueAppending to a nested list adds a new inner list. To add an element to an existing inner list, access that list first:
matrix.append([13, 14, 15])
matrix[0].append(4)Remember that inner lists are mutable objects. If you copy a nested list with copy.copy or slicing, you get a shallow copy; the inner lists are still shared. Use copy.deepcopy when you need independent copies of every level.
Flattening Nested Lists
Flattening converts a nested list into a single-level list. A common approach is a list comprehension with two loops:
flat = [value for row in matrix for value in row]This works when the structure is exactly two levels deep, as in a list of lists. For one level of flattening, itertools.chain.from_iterable(matrix) is equivalent. If the nesting is arbitrarily deep, a recursive generator is more flexible:
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield itemThis handles any nesting depth, but it treats only list instances as containers and has recursion overhead. Choose the method based on the known depth and performance requirements.
Performance and Memory Considerations
Nested lists are straightforward but not always the most efficient structure. Accessing an element is O(1) per index, but iterating over all elements is O(n), where n is the total number of items. Creating a large nested list with comprehensions is generally faster than repeated append calls because it avoids method lookup overhead.
Memory usage depends on the number of inner lists and their sizes. Each inner list is a separate object with its own overhead. If you need a dense rectangular grid, a flat list with manual index arithmetic may use less memory and improve cache locality. For sparse data, a dictionary keyed by coordinates might be more appropriate.
Common Pitfalls and How to Avoid Them
The most frequent bug is creating a nested list with shared inner lists, as mentioned earlier. Another issue is assuming all rows have the same length. When data is irregular, code that expects a rectangular shape will fail. Always validate the structure or use a robust iteration method.
Also be careful with shallow copies when modifying nested lists. If you pass a nested list to a function and modify an inner list, the caller sees the change. Use deepcopy when you need isolation.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.