Python List Assignment Caveat

Posted on January 11, 2011

5


The Problem

In Python, the assignment operator (=) assign the reference to the list instead of making copy of it. The following interaction will demonstrate this concept:

>>> original = [1,2,3]
>>> reference = original # assign the reference
>>> reference
[1, 2, 3]
>>> reference.append(4)
>>> reference
[1, 2, 3, 4]
>>> original
[1, 2, 3, 4]
>>>
  • In line 1, we create a new list, original, with three elements.
  • In line 2, we assign this list to a new variable, reference.
  • In line 5, we append a new value to reference.
  • What happens to the original list? Line 8 and 9 might bring shock to those who are new to Python. What happened?

The answer is the assignment in line 2 assigns the reference to the list so both original and reference will now share the same list and that changes made to one will reflect in the other. So, how do we really make copy of the list instead of sharing the reference?

The Solutions

To make a new copy of a list, there are two different approaches: using the list() function and using the sub list mechanism. The following interactive session will demonstrate the list() function:

>>> original = [1,2,3]
>>> copy = list(original)
>>> copy.append(4)
>>> copy
[1, 2, 3, 4]
>>> original
[1, 2, 3]
>>> 

In line 2, we use the list function to create a copy of the original and assign that list to the variable copy. Any action on copy at that point on will not affect the original list (line 6 and 7)

The following interactive session will demonstrate the sub list feature:

>>> original = [1,2,3]
>>> copy = original[:]
>>> copy.append(4)
>>> copy
[1, 2, 3, 4]
>>> original
[1, 2, 3]
>>> 

Discussion

while both methods accomlish the same goal, many argues that the sub list method is faster. However, the list() function wins point for being easier to understand, especially to new comers.

About these ads
Posted in: Programming, Python