Newbie list question
phawkins at connact.com
phawkins at connact.com
Fri Jul 20 17:33:57 EDT 2001
>>>>> "MA" == Matthew Alton <Matthew.Alton at Anheuser-Busch.COM> writes:
MA> I am a UNIX/C programmer w/15y experience. Forgive me if my neural
MA> pathways are all about following pointers. The adjustment to
MA> Python-think is bumpy but I'll get by with a little help from my
MA> friends, eh?
MA> Here's the crux of the biscuit:
>>>> 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
MA> ['a', 'b', 'c']
>>>> bar
MA> ['a', 'b', 'c']
>>>> baz
MA> ['a', 'b', 'c'] # So far, so good.
>>>> del foo[2] # Get rid of 'c' in foo and, therefore in
MA> bar (?)
>>>> foo
MA> ['a', 'b'] # 'c' is gone from foo...
>>>> bar
MA> ['a', 'b'] # ... and also from bar, as expected.
>>>> baz
MA> ['a', 'b', 'c'] # baz, the copy, is unaffected. Also as
MA> expected.
>>>> foo = foo + ['c'] # Add 'c' back to foo.
You reassigned foo.
foo + ['c'] creates a new object; bar now points to the original
object, foo points to a new and different object. Foo is a label
bound to an object -- think key-value pair, not pointer to an address.
Try foo.append('c')
or foo += 'c'
>>>> foo
MA> ['a', 'b', 'c'] # 'c' is back. Good.
>>>> bar
MA> ['a', 'b'] # ??? What the... ??? Where is 'c'?
>>>> baz
MA> ['a', 'b', 'c'] # baz still unaffected, of course.
>>>>
MA> I have verified this behavior on Python 1.5.1 (AIX 4.3.3) and on
MA> Python 2.1
MA> (Solaris Sparc 2.8). From my arcane perspective, this behavior is
MA> utterly inconsistent and confusing. I strongly suspect that I simply
MA> do not correctly grok the list structure, but so far I am unable to
MA> turn up an explanation in the literature.
MA> Any help is appreciated.
MA> --
Patricia J. Hawkins
Hawkins Internet Applications, LLC
More information about the Python-list
mailing list