My first stumbling block with Python

Andrew Koenig ark at research.att.com
Thu Aug 22 10:41:23 EDT 2002


Neutron> I found the answer by using a list of lists

Neutron> MyArray = [ [0]*512 ]

Neutron> I can now do

Neutron> MyArray [Y][X] = (X,Y,Z) 

Neutron> and it works fine.

No it doesn't:

>>> MyArray = [ [0] * 512 ]
>>> MyArray[12][34] = (1, 2, 3)
IndexError: list index out of range

You probably intended

        MyArray = [ [0]*512 ] *512

but that doesn't work either:

>>> MyArray = [ [0] * 512 ] * 512
>>> MyArray[12][34] = (1, 2, 3)
>>> MyArray[67][34]
(1, 2, 3)

The problem is that the expression [ [0] * 512 ] * 512 is not
512 distinct 512-element lists, as you might think -- rather,
it is 512 references to the same list.  However, you can do this:

        MyArray = [ [0] * 512 for i in range(512) ]

This will reevaluate [0] * 512 each time through the loop.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark



More information about the Python-list mailing list