views:

93

answers:

4

How do I copy the contents of a list and not just a reference to the list in Python?

+5  A: 

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

Lizard
+5  A: 

in addition to the slice notation mentioned by Lizard,

you can use list()

newlist = list(oldlist)

or copy

import copy
newlist = copy.copy(oldlist)
gnibbler
+2  A: 

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().

delnan
+7  A: 

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.

gimel
Note that it's only relevant for containers of mutable data. A list of tuples containing integers gets no benefit from copy.deepcopy while a list with another list in it does.
Nathon