[Tutor] RE: Newbie list question

Tobin, Mark Mark.Tobin@attcanada.com
Fri, 13 Jul 2001 11:21:59 -0600


Does:

foo += 'c'

act like an append then?  I always assumed it was the same as:

foo = foo + 'c'

which obviously should raise a TypeError.  Here however it works, in that it
appends 'c' to the object to which foo refers and thus to the object to
which bar refers...

Mark
-----Original Message-----
From: python-list-admin@python.org
[mailto:python-list-admin@python.org]On Behalf Of Joshua Marshall
Sent: Friday, July 13, 2001 12:52 PM
To: python-list@python.org
Subject: Re: Newbie list question


Matthew Alton <Matthew.Alton@anheuser-busch.com> wrote:
...

>>>> foo = ['a', 'b', 'c']  #  We have a list named 'foo.'  Excellent.
>>>> bar = foo              #  bar points to foo.  Or does it?

bar points to the same object that foo points to.  It's not the case
that bar is an alias for foo.

>>>> baz = foo[:]           #  baz is a copy of foo.

For clarity, it might be better to say baz points to a copy of the
list which foo points to.

>>>> foo
> ['a', 'b', 'c']
>>>> bar 
> ['a', 'b', 'c']
>>>> baz
> ['a', 'b', 'c']            #  So far, so good.
>>>> del foo[2]             #  Get rid of 'c' in foo and, therefore in
> bar (?)
>>>> foo
> ['a', 'b']                 #  'c' is gone from foo...
>>>> bar
> ['a', 'b']                 #  ... and also from bar, as expected.
>>>> baz
> ['a', 'b', 'c']            #  baz, the copy, is unaffected.  Also as
> expected.
>>>> foo = foo + ['c']      #  Add 'c' back to foo.

Here, the variable foo is rebound to a new list.  The previous list
(which bar still points to) is unaffected.  If you had done
"foo.append('c')" instead of "foo = foo + ['c']", than a 'c' would be
appended to the list object that foo and bar both still refer to.
-- 
http://mail.python.org/mailman/listinfo/python-list