Lists & two dimensions

Duncan Smith buzzard at urubu.freeserve.co.uk
Sat Jul 20 09:59:10 EDT 2002


"Pichai Asokan" <asokanp at virtusa.com> wrote in message
news:bed1f696.0207200546.2bca2e34 at posting.google.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?
> Where can we read more to understand what is goingg on?
>
> P Asokan

>>> b = [[-1] * 3 ]
>>> b
[[-1, -1, -1]]                  # a list containing a list
>>> b * 3
[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
>>>
>>> b = [-1] * 3
>>> b
[-1, -1, -1]
>>> b * 3
[-1, -1, -1, -1, -1, -1, -1, -1, -1]
>>>

Maybe

>>> b = ([-1] * 3 ) * 3
>>> b
[-1, -1, -1, -1, -1, -1, -1, -1, -1]

but the braces are not needed.  Does this help?

Duncan





More information about the Python-list mailing list