2

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

Lizard
  • 43,732
  • 39
  • 106
  • 167

4 Answers4

7

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.

Community
  • 1
  • 1
gimel
  • 83,368
  • 10
  • 76
  • 104
  • 4
    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. – nmichaels Jul 20 '10 at 12:40
5

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
  • 43,732
  • 39
  • 106
  • 167
5

in addition to the slice notation mentioned by Lizard,

you can use list()

newlist = list(oldlist)

or copy

import copy
newlist = copy.copy(oldlist)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

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