Assignment binds a name; it does not copy
b = a does not make a second list. It makes the name b refer to the list a already refers to. There is one list with two names. b.append(4) changes that one list, so printing a shows the 4 too, and a is b is True: they are the same object.
a = [1, 2, 3]
b = a # a second name for the same list
b.append(4) # changes that one list, so a sees it too
print(a, a is b)
c = a.copy() # a new list with the same items
c.append(5) # a does not see this
print(a, c)
b = [0] # b now names a different list
print(a, b)
Changing an object vs. pointing a name elsewhere
There are two different things a line can do, and they look alike:
- Mutating the object:
b.append(4),b[0] = 9,b.sort(). Every name that refers to it sees the change. - Rebinding the name:
b = [0]. Onlybnow refers to something else;aand the old list are untouched.
The last lines of the example show the second kind: after b = [0], a is still [1, 2, 3, 4].
Making a real copy
a.copy(), a[:] and list(a) all make a new list with the same items. That is a shallow copy: if the items are themselves lists, the copy refers to the same inner lists. For a list of lists, copy each row ([row[:] for row in grid]) or use copy.deepcopy.
Use is to ask "the same object?" and == to ask "the same value?". A copy is == to its original, but not is.
The classic bug: [[0] * 3] * 3
[0] * 3 makes one row. Multiplying the outer list by 3 does not copy that row; it makes a list of three references to the same row. Set one cell and the whole column changes:
The fix builds a new row each time: [[0] * n for _ in range(n)]. The example below runs both, side by side.
def make_board(n):
board = [[0] * n] * n # bug: one row, n times
board[0][0] = 1 # writes to every row
fixed = [[0] * n for _ in range(n)]
fixed[0][0] = 1
return board
What you see in PyVisualizer
Each list is drawn once, titled with every name that refers to it. After b = a there is one array titled a, b, and b.append(4) adds a cell to it, the one drawing both names share. The copy c gets a drawing of its own, and after b = [0] the shared array is titled a alone while b gets its own. A matrix whose rows are one list gets a warning over it, and every row it shares is marked.
Where it bites
- Function arguments. A function that receives a list receives a reference to the caller's list:
nums.append(x)inside it changes the caller's list too. Rebinding (nums = []) inside it does not. - Default arguments.
def f(seen=[])creates that list once, when the function is defined, and every call shares it. UseNoneand create the list inside. - Backtracking. Appending
pathto the results appends a reference; whenpathchanges later, so does every "saved" answer. Appendpath[:]instead.
Try it yourself
- Swap c = a.copy() for c = a and predict the second print before you run it.
- Paste a function that changes a list it was given, and watch the caller's list change with it.