python - How to clone or copy a list? -
what options clone or copy list in python?
using new_list = my_list modifies new_list every time my_list changes.
 why this?
with new_list = my_list, don't have 2 lists. assignment copies reference list, not actual list, both new_list , my_list refer same list after assignment.
to copy list, have various possibilities:
you can slice it:
new_list = old_list[:]alex martelli's opinion (at least back in 2007) is, it weird syntax , not make sense use ever. ;) (in opinion, next 1 more readable).
you can use built in
list()function:new_list = list(old_list)you can use generic
copy.copy():import copy new_list = copy.copy(old_list)this little slower
list()because has find out datatype ofold_listfirst.if list contains objects , want copy them well, use generic
copy.deepcopy():import copy new_list = copy.deepcopy(old_list)obviously slowest , memory-needing method, unavoidable.
example:
import copy  class foo(object):     def __init__(self, val):          self.val = val      def __repr__(self):         return str(self.val)  foo = foo(1)  = ['foo', foo] b = a[:] c = list(a) d = copy.copy(a) e = copy.deepcopy(a)  # edit orignal list , 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))   result:
original: ['foo', 5, 'baz'] slice: ['foo', 5] list(): ['foo', 5] copy: ['foo', 5] deepcopy: ['foo', 1]      
Comments
Post a Comment