How do I copy the contents of a list and not just a reference to the list in Python?
Use a slice notation.
newlist = oldlist
This will assign a second name to the same list
newlist = oldlist[:]
This will duplicate each element of oldlist into a complete new list called newlist
in addition to the slice notation mentioned by Lizard,
you can use list()
newlist = list(oldlist)
or copy
import copy
newlist = copy.copy(oldlist)
The answes by Lizard and gnibbler are correct, though I'd like to add that all these ways give a shallow copy, i.e.:
l = [[]]
l2 = l[:] // or list(l) or copy.copy(l)
l2[0].append(1)
assert l[0] == [1]
For a deep copy, you need copy.deepcopy().
Look at the copy
module, and notice the difference between shallow and deep copies:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.