Lists & two dimensions
Gregor Lingl
glingl at aon.at
Sat Jul 20 10:46:52 EDT 2002
Pichai Asokan schrieb:
> 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 ...
if you got a list of 9 elements the expression
board[1][2] = 'x'
wouldn't make sense.
>
> What is going on?
> Where can we read more to understand what is goingg on?
What you get is a list of three identical elements (i. e.
three pointers to the same three element list)
like:
>>> l = ['a','b','c']
>>> v = [l]*3
>>> v[1][2]='x'
>>> v
[['a', 'b', 'x'], ['a', 'b', 'x'], ['a', 'b', 'x']]
>>>
a possible workaround:
>>> v = ['a','b','c']
>>> v2 = []
>>> for i in range(3):
v2.append(v[:]) # copy of v
>>> v2
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> v2[2][0]='z'
>>> v2
[['a', 'b', 'c'], ['a', 'b', 'c'], ['z', 'b', 'c']]
>>>
I'm sure there ar more elegant ways ...
Gregor
>
> P Asokan
More information about the Python-list
mailing list