[Tutor] could someone explain why this happens to me.
Emile van Sebille
emile at fenx.com
Sat Mar 7 20:32:16 CET 2009
sphennings W. wrote:
> When I enter the following code into IDLE do both lists have the same value?
They way you've done it, both names List1 and List2 refer/point to the
same list. Changes to one affect both.
> How would I manipulate both lists separately?
Assign them separately or use a copy form of assignment, eg
List2 = List1[:]
Note however that this form of copy doesn't copy nested structures and
you'll have similar issues in that case. Look into deepcopy.
Emile
>
>>>> List1=[1,2,3]
>>>> List2=List1
>>>> List2.reverse()
>>>> print(List2)
> [3, 2, 1]
>>>> print(List1)
> [3, 2, 1]
>>>> List2.append(0)
>>>> print(List2)
> [3, 2, 1, 0]
>>>> print(List1)
> [3, 2, 1, 0]
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list