list.copy()
Returns a new list with the same items. Changing the copy's length or items does not touch the original, but nested lists stay shared.
list.copy()In Python, b = a does not copy a list. It gives the same list a second name, so a change through b shows up in a too. a.copy() builds a new, separate list with the same items.
The copy is shallow: the outer list is new, but the items inside are the very same objects. For numbers and strings that does not matter, because they never change. For lists inside a list it does: change an inner list through the copy and the original sees it too.
When your list holds other lists or dictionaries and you need a fully independent copy, use copy.deepcopy() from the copy module.
Return value
A new list holding the same items, in the same order.
Examples
1A name is not a copy
original = [1, 2, 3]
same = original
same.append(4)
print(original)
separate = original.copy()
separate.append(5)
print(original)
print(separate)[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5]
2Keep the original while you sort
arrivals = ["Omar", "Ana", "Lena"]
by_name = arrivals.copy()
by_name.sort()
print("Arrived:", arrivals)
print("A to Z:", by_name)Arrived: ['Omar', 'Ana', 'Lena'] A to Z: ['Ana', 'Lena', 'Omar']
3The shallow-copy trap with nested lists
grid = [[0, 0], [0, 0]]
shallow = grid.copy()
shallow[0][0] = 9
print(grid)
shallow.append([1, 1])
print(len(grid), len(shallow))[[9, 0], [0, 0]] 2 3
Both lists hold the same inner lists, so changing shallow[0][0] also changes grid. Adding a new row only changes the copy.
4A full copy with deepcopy()
import copy
grid = [[0, 0], [0, 0]]
deep = copy.deepcopy(grid)
deep[0][0] = 9
print(grid)
print(deep)[[0, 0], [0, 0]] [[9, 0], [0, 0]]
Common mistakes
Thinking b = a makes a copy
Assignment never copies. Both names point to one list. Use a.copy(), a[:] or list(a).
a = ["x"]
b = a
b.clear()
print(a)[]
Using copy() on a list of lists
Only the outer list is new. Use copy.deepcopy(), or copy each row: [row.copy() for row in grid].
seats = [["free", "free"], ["free", "free"]]
plan = [row.copy() for row in seats]
plan[1][0] = "taken"
print(seats[1])
print(plan[1])['free', 'free'] ['taken', 'free']
Questions people ask
What is the difference between copy() and deepcopy()?
list.copy() makes a new outer list but shares the items inside. copy.deepcopy() also copies every nested list and dictionary, so nothing is shared.
Is a[:] the same as a.copy()?
Yes. a[:], list(a) and a.copy() all make the same shallow copy. copy() says what it does most clearly.
Why does changing my copy change the original?
Either you did not copy at all (b = a), or the list holds other lists and you made only a shallow copy.