Newbie list question

Joshua Marshall jmarshal at mathworks.com
Fri Jul 13 12:51:53 EDT 2001


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