Variable Scope 2 -- Thanks for 1.
Peter Otten
__peter__ at web.de
Sun Jan 11 14:05:12 EST 2004
Jens Thiede wrote:
> OK, thanks for sorting that out, but what do I replace in the
> following to avoid referancing:
>
> x = [[0]*5]*5
> x is [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]
>
> and after
>
> x[0][0] = 1;
> x is [[1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0]]
>
> is there a shorthand way to avoid referance or do I have to use a loop
> or:
>
> x = [[0]*5]+[[0]*5]+[[0]*5]+[[0]*5]+[[0]*5]
>
> which is obviously stupid to try and do when the second cofficiant is
> large or a variable.
>>> x = [[0]*5 for i in range(5)]
>>> x[0][0] = 1
>>> x
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0,
0, 0, 0]]
or
>>> y = map(list, [[0]*5]*5)
>>> y[0][0] = 1
>>> y
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0,
0, 0, 0]]
>>>
Peter
More information about the Python-list
mailing list