2D lists

Manuel M. Garcia mgarcia at cole-switches.com
Mon Jan 20 15:35:02 EST 2003


On 20 Jan 2003 11:06:47 -0800, marcin at finisar.com (Marcin
Matuszkiewicz) wrote:

>In the code below I created a two dimensional list in two ways.  List
>b behaves I expect, list a does not.  Could someone explain it?
>
>>>> a=[[0]*4]*2
>>>> a
>[[0, 0, 0, 0], [0, 0, 0, 0]]
>>>> a[0][0]=1
>>>> a
>[[1, 0, 0, 0], [1, 0, 0, 0]]
>>>> b=[[0, 0, 0, 0], [0, 0, 0, 0]]
>>>> b[0][0]=1
>>>> b
>[[1, 0, 0, 0], [0, 0, 0, 0]]
>>>>
>
>Thanks,
>
>Marcin

safe way to create a 2 dimensional list initialized with zeros

>>> a = [ [0] * 2 for _ in range(3) ]
>>> a
[[0, 0], [0, 0], [0, 0]]
>>> x = 0
>>> for i in range(3):
... 	for j in range(2):
... 		a[i][j] = x
... 		x += 1
... 		
>>> a
[[0, 1], [2, 3], [4, 5]]

[0] * 2 is a safe way to create a 2 dimensional list, because of the
immutability of 0.

[0] * 2 is not immutable, so [[0] * 2] * 3 is NOT a safe way to create
a 2 dimensional list.

[ x for y in z ] is called a "list comprehension".  It is a recent
addition to Python, and quite handy, but a little strange looking.

The underscore "_" is a standard idiom for a thrown-away value.  This
works just as well:

a = [ [0] * 2 for junk in range(3) ]

Manuel




More information about the Python-list mailing list