Lists & two dimensions

Michael Hudson mwh at python.net
Mon Jul 22 07:23:16 EDT 2002


asokanp at virtusa.com (Pichai Asokan) writes:

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

I hope others have explained that.

> Where can we read more to understand what is goingg on?

This page:

    http://starship.python.net/crew/mwh/hacks/objectthink.html

talks about a different problem, but may help.

Cheers,
M.

-- 
  To summarise the summary of the summary:- people are a problem.
                   -- The Hitch-Hikers Guide to the Galaxy, Episode 12



More information about the Python-list mailing list