-1

How to make a copy of a list ? I have code somewhat as follows :

l = ['1','2','3']
l.pop()

for (x in somerange):
    a = []
    a = l
    a.append("something")

But I don't want the contents of a to reflect in l. How do I make a copy of l and assign it to a.

thegrinner
  • 11,546
  • 5
  • 41
  • 64

1 Answers1

2

You can make a shallow copy of a list (which doesn't copy any contained lists, just references them) by doing this:

a = l[:]

or

import copy
a = copy.copy(l)

The copy module also has a deepcopy function which duplicates any contained mutable objects:

import copy
a = copy.deepcopy(l)

Hope that helps!

Mark R. Wilkins
  • 1,282
  • 7
  • 15