List assignment, unexpected result

Jim Jinkins j-jinkins at usa.net
Mon Jul 8 17:46:17 EDT 2002


Steve Coates wrote:

>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.
>
>Thanks
>Steve
>  
>
The array  rows are  4 references to a single list of 4 columns.  Try 
something like this:

a = [x[:] for x in [['*']*4][:] for y in range(4)]
for ii in range(4): a[ii][ii] = ii

    Jim





More information about the Python-list mailing list