2D lists

Gerrit Holl gerrit at nl.linux.org
Fri Jan 24 20:39:28 CET 2003


Wojtek Walczak schreef op woensdag 22 januari om 14:46:47 +0000:
> Why isn't it mentioned in the FAQ (well, at least it's hard to find) ?
> It's a really frequent question, isn't it ? :)

http://www.python.org/doc/FAQ.html#4.50
4.50. My multidimensional list (array) is broken! What gives?
You probably tried to make a multidimensional array like this.

   A = [[None] * 2] * 3

This makes a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is probably not what you want. The following works much better:

   A = [None]*3
   for i in range(3):
        A[i] = [None] * 2

This generates a list containing 3 different lists of length two.

If you feel weird, you can also do it in the following way:

   w, h = 2, 3
   A = map(lambda i,w=w: [None] * w, range(h))

For Python 2.0 the above can be spelled using a list comprehension:

   w,h = 2,3
   A = [ [None]*w for i in range(h) ]

yours,
Gerrit.

-- 
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list