List assignment, unexpected result

Steve Coates steve.coates at talk21.com
Mon Jul 8 16:20:15 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.

Thanks
Steve



More information about the Python-list mailing list