Bay Area Python Interest Group August 2007 Meeting
37 4 10180
August 2007 Meeting of the Bay Area Python Interest Group; Python Newbies night, featuring the second half of Alex Martelli's talk on "Python for Programmers."
By anonymous 2017-09-20
new_list = my_list, you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both
my_list refer to the same list after the assignment.
To actually copy the list, you have various possibilities:
You can slice it:
new_list = old_list[:]
You can use the built in
new_list = list(old_list)
You can use generic
import copy new_list = copy.copy(old_list)
This is a little slower than
list()because it has to find out the datatype of
If the list contains objects and you want to copy them as well, use generic
import copy new_list = copy.deepcopy(old_list)
Obviously the slowest and most memory-needing method, but sometimes unavoidable.
import copy class Foo(object): def __init__(self, val): self.val = val def __repr__(self): return str(self.val) foo = Foo(1) a = ['foo', foo] b = a[:] c = list(a) d = copy.copy(a) e = copy.deepcopy(a) # edit orignal list and instance a.append('baz') foo.val = 5 print('original: %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r' % (a, b, c, d, e))
original: ['foo', 5, 'baz'] slice: ['foo', 5] list(): ['foo', 5] copy: ['foo', 5] deepcopy: ['foo', 1]