Newbie list question

Tobin, Mark Mark.Tobin at attcanada.com
Fri Jul 13 13:34:33 EDT 2001


But when I run:

>>> foo = ['a', 'b', 'c']
>>> bar = foo
>>> baz = foo[:]
>>> del foo[2]
>>> foo
['a', 'b']
>>> bar
['a', 'b']
>>> foo += 'c'
>>> foo
['a', 'b', 'c']
>>> bar
['a', 'b', 'c']
>>> 

which doesn't happen when you use foo = foo + ['c']
right? That was the point of his original question, or am I all messed up?

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



It is my understanding that the C-like "+=" was added
at 2.0 as syntactic sugar.  It is syntactically equivalent.

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


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 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.
-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list