Assigning a list to a second name does not copy it. Watch two names share one list, then see how copy() makes a separate one.
Python · beginner · 8 min · 8 steps · free
copy() to get an independent lista = [1, 2, 3]
b = a
b.append(4)
print(a)
c = a.copy()
c.append(5)
print(a)
print(c)a point to it. The name and the list are two separate things.b = a does not copy the list. It makes a second name, b, point to the very same list object. There is still only one list.b.append(4) adds 4 to the list that b points to. Because a points to that same list, a sees the change too.a shows four items, even though the code never called a.append. Both names lead to the one list that was changed.a.copy() builds a brand new list with the same items, and c points to that new list. Now there are two list objects.c.append(5) changes only the new list. The original list that a and b share is left alone.a still has four items. Appending to the copy did not touch it.c has five items. Use copy() whenever you want a list you can change without affecting the original.backup = items and expecting backup to keep the old contentslist.copy() or list(items) when you need a separate listcopy.deepcopy(); copy() only copies the outer listb = a gives the same list a second name; it does not copy it.a.copy() or list(a) when you need an independent list.x = [1], y = x and y.append(2), what is x?Answer: [1, 2]. x and y are two names for one list, so the append shows through both.
Answer: b = a.copy(). copy() builds a new list; plain assignment only adds a name.
← Slicing Lists · Tuples and Unpacking →