List assignment, unexpected result

Mark McEahern marklists at mceahern.com
Mon Jul 8 16:57:30 EDT 2002


> A friend of mine recently sent me some code and asked if I could
> predict what it would do. I guessed wrong. Code as follows:-
>
> grid = [['.'] * 4 ] * 4
> grid [0][0] = '0'
> grid [1][1] = '1'
> grid [2][2] = '2'
> grid [3][3] = '3'
> for i in grid: print i
>
> The intent is clear i.e. fill the diagonal with 0,1,2,3; but the
> result is somewhat different. Could anyone explain why this doesn't
> work as expected - and even better, come up with an assignment for
> 'grid' that would work. My only suggestion was an explicit
> [['.','.','.','.'],['.','.','.','.'],etc. but it gets a bit cumbersome
> for large grids.

You can do multidimensional arrays by writing your own class or you can use
the Numeric package:

	http://numpy.sf.net/

// m

-






More information about the Python-list mailing list