[Tutor] could someone explain why this happens to me.

Kapsicum duakapil at gmail.com
Sat Mar 7 20:36:38 CET 2009


On Sun, Mar 8, 2009 at 12:39 AM, sphennings W. <sphennings at gmail.com> wrote:

> When I enter the following code into IDLE  do both lists have the same
> value?
> How would I manipulate both lists separately?
>
> >>> 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]


When you create an object and assign it to a variable, the variable only
refers to the object
and does not represent the object itself.


If you want to make a copy of a list or such kinds of sequences , then you
have to use
the slicing operation to make a copy. If you just assign the variable name
to another name,
both of them will refer to the same object.

List2=List1[ : ]



Kapil Dua
Mobile: +919711311052
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090308/b62b3641/attachment.htm>


More information about the Tutor mailing list