[Tutor] Weird list indexing

Zak Arntson zak@harlekin-maus.com
Wed Jul 9 17:14:01 2003


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?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em