Lists and References

A variable does not hold a list directly. It holds a reference, which points to the list. When you write shared = original, Python copies the reference. It does not copy the list.

original = [120, 95, 42]
shared = original
shared.append(4)

backup = original.copy()
backup.append(1)

print(original)
print(backup)

Output:

[120, 95, 42, 4]
[120, 95, 42, 4, 1]

shared and original are two names for the same list. So when you append through shared, you see the change through original too. copy() makes a new, separate list with the same values. That is why appending to backup does not change original.

The shared default list

This sharing also causes a common mistake with functions. Python creates a default value only once, when it defines the function. So if the default is a list, every call uses that same list:

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

print(add_item("tea"))
print(add_item("milk"))

Output:

['tea']
['tea', 'milk']

The second call did not start with an empty list. It still had 'tea' from the first call. To avoid this, use None as the default, and create a new list inside the function.

In the exercise, make a backup that is a real, separate copy.