Newbie list question

Mikael Olofsson mikael at isy.liu.se
Fri Jul 13 19:13:49 CEST 2001


Hi Matthew!

Welcome to the world of Python.

On 13-Jul-2001 Matthew Alton wrote:
 >  I am a UNIX/C programmer w/15y experience.  Forgive me if my neural
 >  pathways are all about following pointers.  The adjustment to
 >  Python-think is bumpy but I'll get by with a little help from my
 >  friends, eh?

Before we start; everything is a pointer in Python.

 >  Here's the crux of the biscuit:
 >  
 > >>> foo = ['a', 'b', 'c']  #  We have a list named 'foo.'  Excellent.

Actually, we have a pointer foo pointing to a list of pointers to 
the strings 'a', 'b', and 'c'.

 > >>> bar = foo              #  bar points to foo.  Or does it?

We copy the pointer foo. So bar now points to the same list as foo.

 > >>> baz = foo[:]           #  baz is a copy of foo.

baz points to a copy of the list. However, that list still points to 
the same strings...

The pointer stuff explains the following.

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

But now things happen:

 > >>> foo = foo + ['c']      #  Add 'c' back to foo.

The RHS creates a new list containing pointers to strings 'a', 'b', and
'c'. The LHS binds foo to this new list, i.e. foo now points to the new
list. You have not done anything to bar. 

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

I suggest that you go through your code again and try id(foo), id(bar),
and id(baz) here and there. The function id(pointer) returns an integer,
basically the address of pointer.

All this is documented behaviour. However, I do not have the time to find 
it for you right now. I'm sorry.

Good luck
/Mikael

-----------------------------------------------------------------------
E-Mail:  Mikael Olofsson <mikael at isy.liu.se>
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date:    13-Jul-2001
Time:    18:59:45

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by XF-Mail.
-----------------------------------------------------------------------




More information about the Python-list mailing list