[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 

>>> aa=range(0,10)
>>> bb=aa
>>> id(aa)
>>> id(bb)

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

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
>>> aa==cc   # note: aa is equal to cc
>>> aa is cc # but they're not the same object

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
>>> aa==dd   # note: aa is equal to dd
>>> aa is dd # but they're not the same object

More information about the Tutor mailing list