[Tutor] Weird list indexing

Eric L Howard elh@outreachnetworks.com
Wed Jul 9 17:52:05 2003


At a certain time, now past [Jul.09.2003-02:13:29PM -0700], zak@harlekin-maus.com spake thusly:
> Okay, I create a 2-d "array" like so:
> 
> ###
> 
> >>> a = [[None, None, None], [None, None, None], [None, None, None]]
> >>> a
> [[None, None, None], [None, None, None], [None, None, None]]
> >>> a[1][2] = 'a'
> >>> a
> [[None, None, None], [None, None, 'a'], [None, None, None]]
> 
> ###
> 
> This makes sense. Now, why does this happen? I'm using Python 2.2.3, by
> the way.
> 
> ###
> 
> >>> a = [[None] * 3] * 3
> >>> a
> [[None, None, None], [None, None, None], [None, None, None]]
> >>> a[1][2] = 'a'
> >>> a
> [[None, None, 'a'], [None, None, 'a'], [None, None, 'a']]
> 
> ###
> 
> My guess is that the three lists are all the same object, just pointed to
> three different times? So it seems my shortcut to create a two-dimensional
> array doesn't work. Is there better shortcut?

I can't say anything towards the 'better shortcut', but....the first thing
that came to mind to see if it was the same object [my first guess also] was
id().

>>> a = [[None] * 3] * 3
>>> a
[[None, None, None], [None, None, None], [None, None, None]]
>>> a[1][2] = 'a'
>>> a
[[None, None, 'a'], [None, None, 'a'], [None, None, 'a']]
>>> id(a)
135424172
>>> id(a[0])
135627396
>>> id(a[1])
135627396
>>> id(a[2])
135627396

       ~elh

-- 
Eric L. Howard           e l h @ o u t r e a c h n e t w o r k s . c o m
------------------------------------------------------------------------
www.OutreachNetworks.com                                    313.297.9900
------------------------------------------------------------------------
JabberID: elh@jabber.org                 Advocate of the Theocratic Rule