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

One Response

  1. […] daily pitfall celebrates array copying. In a previous post, we talked about copying lists. If you’re using a numpy array (ndarray), however, the correct way to do it is using […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: