Thursday, October 14, 2010

[Py] Assign values of one list to another

It is easy to ``copy'' lists in Python, but it is also easy to get things wrong, especially when you ignore something important like what I did.

Consider the following situation:
>>> A = [1,2,3]
>>> B = A
>>> B[0]=-1
>>> A
[-1, 2, 3]

What I want is to create a new list B which contains identical elements of the original list A. This doesn't work, however. As you can see in the above test, any modifications made on list B will affect list A. The reason is that when we type ``B=A'', the list B is just another name of list A. They are identical and of course are pointed to the same address. See the following tests:

>>> B is A
>>> B.index, A.index
(, )

So, if we need an independent list B which has a set of values' copy in list A, use ``list slicing'':
>>> B = A[:]
>>> B is A
>>> B.index, A.index
(, )
Ref: An Introduction to Python Lists

No comments:

Post a Comment