Skip to content
← Back to all articles
For Developers

Python Nested List Shared References: How to Fix Unexpected List Mutations

Python lists are flexible data structures used in backend applications, automation scripts, data processing, machine learning and software development.

However, creating nested lists using multiplication can introduce an unexpected bug. Changing one element may appear to modify multiple rows simultaneously.

This behavior is caused by shared references to mutable objects.

Understanding Python nested list shared references can help developers prevent subtle bugs and build more reliable applications.

1. Reproducing the Python nested list bug

Suppose you want to create a three-row grid with two columns.

You might write:

grid = [[0] * 2] * 3
print(grid)

Output:

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

Initially, the grid looks correct.

Now change the second element of the first row:

grid[0][1] = 7
print(grid)

Output:

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

Every row appears to have changed, even though only one assignment was performed.

2. Why does Python list multiplication behave this way?

Python lists contain references to objects.

When a list is multiplied by an integer, Python repeats the references contained in that list. It does not recursively create independent copies of every referenced object.

Consider this equivalent implementation:

row = [0, 0]
grid = [row] * 3

The outer list contains three references to the same row object.

Conceptually:

grid[0] → row
grid[1] → row
grid[2] → row

When you modify the row through any of these references, the other references observe the same modified object.

The inner list is mutable, which makes this shared-reference behavior visible.

3. Verify the problem using object identity

Python provides the is operator to check whether two references point to the same object.

grid = [[0] * 2] * 3

print(grid[0] is grid[1])
print(grid[1] is grid[2])

Output:

True
True

Both comparisons return True because all three positions reference the same inner list.

Object identity vs equality

The equality operator compares values.

The is operator compares object identity.

a = [0, 0]
b = [0, 0]

print(a == b)
print(a is b)

Output:

True
False

The lists contain equal values but are independent objects.

This distinction is important when debugging unexpected mutations.

4. Fix shared references using list comprehension

The recommended approach for creating independent rows is to use list comprehension.

grid = [[0] * 2 for _ in range(3)]

grid[0][1] = 7

print(grid)

Output:

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

The inner expression is evaluated separately for each iteration, creating a new list every time.

You can verify this behavior:

print(grid[0] is grid[1])

Output:

False

Now each row can be modified independently.

Creating a reusable grid function

def create_grid(rows, columns):
    return [
        [0] * columns
        for _ in range(rows)
    ]

grid = create_grid(3, 2)
grid[0][1] = 7

print(grid)

This function creates independent rows containing immutable integer values.

If your cells need to contain mutable objects, such as dictionaries or lists, create each cell independently as well.

grid = [
    [{} for _ in range(2)]
    for _ in range(3)
]

Each cell now contains a distinct dictionary.

5. Understanding shallow copies in Python

A shallow copy creates a new outer container while preserving references to the original nested objects.

original = [[1, 2], [3, 4]]
copied = original.copy()

copied[0][0] = 99

print(original)

Output:

[[99, 2], [3, 4]]

Although copied is a new outer list, both containers reference the same inner lists.

The following approaches also create shallow copies of lists:

copied = original[:]
copied = list(original)

They do not recursively copy nested mutable objects.

Copying individual rows

For a two-dimensional grid containing immutable values, copying each row is sufficient.

original = [[1, 2], [3, 4]]

copied = [
    row.copy()
    for row in original
]

copied[0][0] = 99

print(original)
print(copied)

Output:

[[1, 2], [3, 4]]
[[99, 2], [3, 4]]

The original and copied rows are independent.

However, if individual cells contain mutable objects, copying only the rows may still leave shared references at deeper levels.

6. When should you use deepcopy?

Python’s copy module provides deepcopy for recursively copying supported objects.

from copy import deepcopy

original = [
    {"items": [1, 2]},
    {"items": [3, 4]}
]

copied = deepcopy(original)

copied[0]["items"].append(99)

print(original)
print(copied)

The original nested items remain unchanged.

Deep copying is useful when working with nested configuration data, complex application state or structures that require independent copies.

However, deepcopy can consume additional memory and processing time.

It also preserves shared-reference relationships within the copied object graph. Therefore, deep copying an already-aliased grid does not necessarily make its rows independent.

from copy import deepcopy

original = [[0, 0]] * 3
copied = deepcopy(original)

print(copied[0] is copied[1])

Output:

True

The copied grid is separate from the original grid, but its own rows still share an inner object.

If independent rows are required, construct them independently.

7. Another common Python mutable-object mistake

Shared references can also appear when using mutable default function arguments.

Consider:

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("React"))
print(add_item("Python"))

Output:

['React']
['React', 'Python']

The default list is created when the function is defined, rather than on every call.

Use None as the default when a new list is needed for each invocation.

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

This creates a new list whenever the caller does not provide one.

The underlying lesson is similar: understand when mutable objects are created and whether references are being reused.

8. Real-world applications

Game development

A chessboard or grid-based game requires independently editable rows.

board = [
    [None] * 8
    for _ in range(8)
]

Data processing

Independent buffers prevent records from one group from accidentally appearing in another.

buffers = [
    [] for _ in range(5)
]

Backend applications

When constructing nested response objects, create separate dictionaries for records that will be modified independently.

records = [
    {"status": "pending"}
    for _ in range(3)
]

AI and automation

Independent containers are useful when collecting results from different processing tasks or maintaining separate workflow states.

The same reference-handling principles apply to ordinary Python data structures used in these systems.

9. Write regression tests for shared-reference bugs

Testing only the initial grid values is insufficient because a broken grid may look correct before mutation.

Instead, test the behavior after updating one row.

def test_grid_rows_are_independent():
    grid = [
        [0] * 2
        for _ in range(3)
    ]

    grid[0][1] = 7

    assert grid[0] == [0, 7]
    assert grid[1] == [0, 0]
    assert grid[2] == [0, 0]
    assert grid[0] is not grid[1]

This test checks both the expected values and object independence.

For more deeply nested structures, test mutations at the levels where independence is required.

10. Best practices for Python mutable objects

Frequently Asked Questions

Is Python list multiplication always unsafe?

No. Repeating immutable values, such as integers or strings, is generally appropriate. Problems arise when repeated references point to mutable objects that are expected to be independent.

Why does list comprehension fix nested list aliasing?

When the expression constructs a new list, each iteration creates a separate object. However, a comprehension that repeatedly returns an existing object can still create shared references.

Does list.copy create independent nested lists?

No. It creates a shallow copy of the outer list and preserves references to nested objects.

Is deepcopy always the best solution?

No. It may introduce unnecessary overhead and preserves shared relationships within the copied graph. Choose a copying strategy based on the required object structure.

How can I detect shared references?

Use the is operator to compare object identity. You can also use Python’s id function when inspecting objects during debugging.

Conclusion

Python nested list shared references are a common source of unexpected mutations.

List multiplication repeats references rather than independently creating nested objects. When independent rows are required, use list comprehension or an appropriate factory function.

Understanding object identity, shallow copying and deep copying helps developers avoid subtle bugs in backend applications, automation scripts and data processing systems.

Test how your data structures behave after mutation, not only how they look when initially created.

Need assistance debugging Python applications, developing backend APIs, implementing automation or building AI-powered solutions? Connect with Tekody for professional remote engineering and AI development support.

👉 Request Support: https://tekody.com/get-support/

📲 WhatsApp for Support: +91-8527854783

Need help with a similar challenge?

Discuss your requirements with Tekody and explore practical support options.