In Python, assignment is in fact putting a name label (sticker) on an object. So if we want to copy a list, and we write the following code:
a = SomeList b = a
a
and b
are actually two different labels for the object SomeList
… and accordingly, changing the value of a
will also change the value of b
!
If we want to copy a list properly, we can use any of the following:
listB = listA[:]
or
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)
Filed under: python | Tagged: list copy, lists, python | 2 Comments »