Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~3 min readPython
#nested lists#list comprehension#flattening#iteration
Illustration of a nested list structure in Python showing a list containing multiple lists, with elements highlighted.

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:

python
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:

python
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:

python
matrix[0][1] # returns 2

You 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:

python
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:

python
matrix[0] = [10, 11, 12] # replace first row matrix[1][2] = 99 # change a single value

Appending to a nested list adds a new inner list. To add an element to an existing inner list, access that list first:

python
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:

python
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:

python
def flatten(nested): for item in nested: if isinstance(item, list): yield from flatten(item) else: yield item

This 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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.