Newbie list question
Mark Day
mday at apple.com
Fri Jul 13 13:14:28 EDT 2001
In article <13c69f60.0107130843.5cd7dc38 at posting.google.com>, 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?
> >>> baz = foo[:] # baz is a copy of foo.
> >>> 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.
> >>> foo
> ['a', 'b', 'c'] # 'c' is back. Good.
> >>> bar
> ['a', 'b'] # ??? What the... ??? Where is 'c'?
> >>> baz
> ['a', 'b', 'c'] # baz still unaffected, of course.
> >>>
The statement:
foo = foo + ['c']
creates a brand new list from the contents of foo and the list ['c']
and assigns the new list to foo.
If you had instead done:
foo.append('c')
then it would have changed the list that foo and bar were both pointing
at.
-Mark
More information about the Python-list
mailing list