[Tutor] Python oddity
Terry Carroll
carroll at tjc.com
Thu Feb 28 03:12:18 CET 2008
On Wed, 27 Feb 2008, Keith Suda-Cederquist wrote:
> Hi,
>
> I'm using iPython and I've run into an occasional problem that I don't
> understand. Here is what I'm seeing:
>
> >>aa=range(0,10)
> >>bb=aa
> >>print aa
> [0,1,2,3,4,5,6,7,8,9]
> >>print bb
> [0,1,2,3,4,5,6,7,8,9]
> >> # okay, everything allright at this point
> >>bb[5]=0 #change bb
> >>print aa
> [0,1,2,3,4,0,6,7,8,9] #aa has changed!!!
> >>print bb
> [0,1,2,3,4,0,6,7,8,9]
>
> So the problem is that when I change bb, aa also changes even though I
> don't want it to. Is this supposed to happen? If it is can someone
> explain to me why this is a good thing? and finally, can someone give
> me some advice on how to avoid or work-around this problem.
In addition to Luke's comments, let me try it from a slightly different
angle:
>>> aa=range(0,10)
>>> bb=aa
>>> id(aa)
12169048
>>> id(bb)
12169048
The id() function provides the unique ID number of an object. Note that
aa and bb have the same ID; they are just two names for the same object.
Once you realize that, it will be more clear that a change to aa is also a
change to bb.
In fact, here's something that really drives home they're the same object:
>>> aa is bb
True
Instead of using the assignment statement, which just puts a new label on
an object, you can subject your list to an operation that produces another
list that is identical to the list it operates on.
One example:
>>> cc=list(aa)
list() takes something as input and produces list from it. if you hand a
list to list() you get a new list (i.e., a new object) that is identical
to the list that was input.
>>> id(cc) # note: new object id
12185688
>>> aa==cc # note: aa is equal to cc
True
>>> aa is cc # but they're not the same object
False
Another approach is to take a list "slice" that just happens to slice out
the entire list:
>>> dd=aa[:]
>>> id(dd) # note: new object id
12168408
>>> aa==dd # note: aa is equal to dd
True
>>> aa is dd # but they're not the same object
False
More information about the Tutor
mailing list