How to copy a list in Python?
Let me tell about a common mistake many python beginners do while trying to copy a list to another list. Suppose to copy a list listA to listB, they use
Here I paste some experiments I made:
Hope you get the point!
listB = listA
, now if you change something in one list, the other list is changed automatically as they refer to same list - actually listB points to listA! So the proper way should belistB = []
listB.extend(listA)
Here I paste some experiments I made:
>>> listA = [1, 2, 3, 4, 5]
>>> listB = listA
>>> listC = []
>>> listC.extend(listA)
>>> listB
[1, 2, 3, 4, 5]
>>> listC
[1, 2, 3, 4, 5]
>>> listA
[1, 2, 3, 4, 5]
>>> listB[4] = 0
>>> listB
[1, 2, 3, 4, 0]
>>> listA
[1, 2, 3, 4, 0]
>>> listC
[1, 2, 3, 4, 5]
>>> listC[4] = 10
>>> listC
[1, 2, 3, 4, 10]
>>> listA
[1, 2, 3, 4, 0]
>>> listB
[1, 2, 3, 4, 0]
>>>
Hope you get the point!
Comments
listB = list(listA)
or
from copy import copy
listB = copy(listA)
if the list contains other lists as elements or other mutable objects, these objects are not copied but also shared so you might run into similar problems on these objects. In that case the following helps:
from copy import deepcopy
listB = deepcopy(listA)
Does anyone know why Python has this feature? I suppose multiple pointers to the same memory locations could be useful in some parallel programming applications, but it seems odd to make this the default.
In Python, assignment is in fact putting a name label (sticker) on an object. So
a = SomeList
b = a
first puts the label 'a' on SomeList, and after that it puts label 'b' on the same object. So SomeList has two labels attached to it.