DEV Community

Discussion on: How to copy a list in Python

Collapse
 
rhymes profile image
rhymes

Hi @cuongld2 !

Another way is to use the unpacking operator:

>>> ls1 = list(range(10))
>>> ls1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls2 = [*ls1]
>>> ls2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> id(ls1), id(ls2)
(4315161728, 4315161152)

Don't forget you're performing a shallow copy though, if the list contains an object, you're sharing the same object between the original list and the copy:

>>> ls3 = [ls1]
>>> ls4 = ls3[:]
>>> ls3, ls4
([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> ls4[0].append(10)
>>> ls3, ls4
([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])

as you can see now both lists, the original and the copy, have been modified, this is because the list contain a share object (the list ls1). If you want a deep copy you can use copy.deepcopy():

>>> ls3 = [list(range(5))]
>>> import copy; ls4 = copy.deepcopy(ls3)
>>> ls3, ls4
([[0, 1, 2, 3, 4]], [[0, 1, 2, 3, 4]])
>>> ls4[0].append(10)
>>> ls3, ls4
([[0, 1, 2, 3, 4]], [[0, 1, 2, 3, 4, 10]])

There are limitations to what it can "deepcopy", the documentation contains further details.

Collapse
 
paddy3118 profile image
Paddy3118

Please don't use list unpacking for the sole purpose of creating a shallow copy of a list. Lists have a .copy method that should be used.

Collapse
 
rhymes profile image
rhymes

I agree, my fault :) I was enumerating the various options :)