FW: Newbie list question

Tobin, Mark Mark.Tobin at attcanada.com
Fri Jul 13 19:26:44 CEST 2001

Whoops wrong list...

-----Original Message-----
From: Tobin, Mark 
Sent: Friday, July 13, 2001 1:22 PM
To: 'Joshua Marshall'; 'Matthew.alton at anheuser-busch.com';
'tutor at python.org'
Subject: RE: Newbie list question


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...

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

Matthew Alton <Matthew.Alton at 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.

More information about the Python-list mailing list