[Tutor] Initializing array (was Round Robin)

Christopher Smith csmith@blakeschool.org
Wed, 20 Jun 2001 13:03:42 -0500


Chris wrote:

> Here's an alternate way to initialize an array (i.e. list of lists)
>  # function to initialize array
>   def make_array(r,c):
>     a=[]
>     for i in range(r):
>       a.append([])
>       for ii in range(c):
>         a[i].append(0)
>     return a

Or how about simply:

	for i in range(r):a.append([0]*c)

But not

	a=[[0]*c]*r

Since the latter creates aliases--look at the following interpreted
session:  

>>> r=2;c=3
>>> a=[[0]*c]*r
>>> a[1][1]=2;a
[[0, 2, 0], [0, 2, 0]]
>>>

You only set a[1][1] to 2 but all a[i][1] values are the same (apparently).

If you use the former code then type the following in the interpreter:

>>> a=[]
>>> for i in range(r):a.append([0]*c)
... 
>>> a[1][1]=2;a
[[0, 0, 0], [0, 2, 0]]
>>>

you obtain a different (perhaps more desired) result.

/c