List assignment, unexpected result

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Mon Jul 8 16:40:06 EDT 2002


steve.coates at talk21.com (Steve Coates) writes:
> grid = [['.'] * 4 ] * 4

This is the same as saying:

  x = ['.' * 4]
  grid = [x, x, x, x]

That is, the 4 elements of grid are all the same list.  If you now

> grid [0][0] = '0'
> grid [1][1] = '1'

This is like:

   x[0] = '0'
   x[1] = '1'

so now all 4 elements of grid are ['0','1','.','.']

> 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.

  grid = [['.' * 4] for i in range(4)]

is one way.  

IMO this issue should be in the Python warts list (I'm not sure if
it's currently on the list or not).



More information about the Python-list mailing list