List assignment, unexpected result

Christophe Delord christophe.delord at free.fr
Mon Jul 8 16:49:56 EDT 2002


On 8 Jul 2002 13:20:15 -0700
steve.coates at talk21.com (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

The problem is that ['.'] * 4 is instanciated 1 time and grid is a list containing 4 "pointers" to the same sublist.
Decompose it like this:
	row = ['.'] * 4
	grid = row * 4

so grid[1][1] = '1' is equivalent to row[1] = '1'
because (grid[1])[1] is row[1]

so grid is now [ '.', '1', '.', '.' ] * 4

The solution is to instanciate 4 different rows like this for example :

grid = [ [ '.' for x in range(4) ] for y in range(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


-- 

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V



More information about the Python-list mailing list