Lists & two dimensions
Chris Gonnerman
chris.gonnerman at newcenturycomputers.net
Sat Jul 20 10:00:02 EDT 2002
----- Original Message -----
From: "Pichai Asokan" <asokanp at virtusa.com>
> I am a trainer and in a training session a participant came up with a
> problem that stumped me:
>
> Here is the code snippet that isolates what I want:
> --------------------
> board = [[-1] * 3 ]*3
> print board
> board[1][2] = 'x'
> print board
> --------------------
> Output
> -----------------------
> [ [-1, -1, -1 ], [-1, -1, -1 ], [-1, -1, -1 ] ]
> [ [-1, -1, 'x'], [-1, -1, 'x'], [-1, -1, 'x'] ]
> -----------------------
>
> I thought
> board = [[-1] * 3 ]*3
> should give me a list of 9 elements;
> but ...
>
> What is going on?
Multiplication of a list by N results in N references to the
same list. The inner list contains (references) scalars, so
each slot is effectively independent, but the outer list
contains lists... so there you go.
> Where can we read more to understand what is goingg on?
This is a FAQ I think; go to www.python.org and take a look
there. (Or someone else may post the pointer if you are
lucky).
Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net
http://newcenturycomputers.net
More information about the Python-list
mailing list