Question:
What are the options to clone or copy a list in Python?
While using
What are the options to clone or copy a list in Python?
While using
new_list = my_list
, any modifications to new_list
changes my_list
every time. Why is this?
Best Answer:
With
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 new_list
and my_list
refer to the same list after the assignment.
To actually copy the list, you have various possibilities:
- You can use the builtin
list.copy()
method (available since Python 3.3): - You can slice it:Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable).
- You can use the built in
list()
function: - You can use generic
copy.copy()
:This is a little slower thanlist()
because it has to find out the datatype ofold_list
first. - If the list contains objects and you want to copy them as well, use generic
copy.deepcopy()
:Obviously the slowest and most memory-needing method, but sometimes unavoidable.
new_list = old_list.copy()
new_list = old_list[:]
new_list = list(old_list)
import copy
new_list = copy.copy(old_list)
new_list = copy.copy(old_list)
import copy
new_list = copy.deepcopy(old_list)
new_list = copy.deepcopy(old_list)
Example:
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.copy()
c = a[:]
d = list(a)
e = copy.copy(a)
f = copy.deepcopy(a)
# edit orignal list and instance
a.append('baz')
foo.val = 5
print('original: %r\n list.copy(): %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r'
% (a, b, c, d, e, f))
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.copy()
c = a[:]
d = list(a)
e = copy.copy(a)
f = copy.deepcopy(a)
# edit orignal list and instance
a.append('baz')
foo.val = 5
print('original: %r\n list.copy(): %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r'
% (a, b, c, d, e, f))
Result:
original: ['foo', 5, 'baz']
list.copy(): ['foo', 5]
slice: ['foo', 5]
list(): ['foo', 5]
copy: ['foo', 5]
deepcopy: ['foo', 1]
list.copy(): ['foo', 5]
slice: ['foo', 5]
list(): ['foo', 5]
copy: ['foo', 5]
deepcopy: ['foo', 1]
No comments:
Post a Comment