Python modifying list side effects

When modifying a list, be aware of possible side effects. Let's say we define a list and then let another variable reference it. Then these two variables refer to the same object in memory.

This example has side effects in b, because assignment does not create a new object:

# Add three to all list members.
a = [3, 4, 5]
b = a                     # a and b refer to the same list object

for i in range(len(a)):
    a[i] += 3             # b[i] also changes

print(a == b)             # True

But this example does not because the list comprehension creates a new list object:

a = [3, 4, 5]
b = a

# assign the variable "a" to a new list without changing "b"
a = [i + 3 for i in a]
print(a == b)  # False

FYI: if we instead use the slice assignment syntax (a[::]), we do not create a new object but modify the original list in place so that list b is changed as a side effect. In this case both variables still refer to the same object:

a = [3, 4, 5]
b = a

# assign the variable "a" to a new list without changing "b"
a[::] = [i + 3 for i in a]
print(a == b)  # True

You won't see this syntax much in practice because the point of b = a is almost certainly to keep a backup copy of a before it is modified. TLDR; to avoid side effects it's safer to just make a new list object.