[Tutor] Initializing a list as an array

Kirby Urner urnerk@qwest.net
Sat, 08 Dec 2001 08:44:57 -0800


>
>Just a little warning here, this doesn't extend to multidimensional
>lists:
> >>> mymatrix = [[0]*3]*3
> >>> mymatrix
>[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Excellent point re a common pitfall for new Python
programmers, Kalle.  Your example is very clear.


>Finally, code that does the thing you might expect from the example above:
>
> >>> mymatrix = [[0] * 3 for x in xrange(3)]
> >>> mymatrix[0][0] = 1
> >>> mymatrix
>[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

...as is your solution.

Kirby