Variable Scope 2 -- Thanks for 1.

Francis Avila francisgavila at yahoo.com
Sun Jan 11 20:17:47 CET 2004


Jens Thiede wrote in message ...
>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]]

Ah, the joy of list comprehensions!

>>> x = [ [ 0 for i in range(5)] for j in range(5)]
>>> x
[[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]]
>>> 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]]
>>>

There are other ways, but using list comprehensions is the usual idiom now.

--
Francis Avila




More information about the Python-list mailing list