Copying lists in Python

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)
Advertisements

List Slicing (last index minus 1)

Stupid bug caused because I didn’t remember this very simple fact! Suppose we have a list:

mylist = [1,2,3,4,5]

And we want to slice only the first two elements: [1,2].
Writing this:

print mylist[0:1]

will actually only give us this:

[1]

If we want to print the first two elements, we need to write

print mylist[0:2]

and then we get

[1,2]

because Python always selects the last index minus 1.