[Tutor] Python oddity

Brett Wilkins lupin at orcon.net.nz
Thu Feb 28 10:03:28 CET 2008


As everybody else has told you, assigning bb = aa just gives bb the 
reference to the same object that aa has. Unless I missed something, 
then nobody's actually mentioned how to make this not happen... and it's 
actually rather easy... instead of bb = aa, do this:
bb = aa[:]
Looks like a splice, and indeed it is a splice, without bounds. When a 
splice is used like this, I believe it is known as the copy directive.

See, when you start to do an assignment to an action on a variable (eg 
bb = aa*4, where a is a number, for example) bb then references an 
entirely new object. so, the boundless splice on aa from your examples 
would return a fresh copy of the original object stored in aa.

Hope this helped,

Brett

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.
>
> Thanks,
> Keith
>
> ------------------------------------------------------------------------
> Looking for last minute shopping deals? Find them fast with Yahoo! 
> Search. 
> <http://us.rd.yahoo.com/evt=51734/*http://tools.search.yahoo.com/newsearch/category.php?category=shopping> 
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


More information about the Tutor mailing list