On Thu, 19 Jan 1995, Aaron Watters wrote:
> The fix to avoid shared references is just a bit less elegant,
> but not too bad:
> >>> arr = [None]*4
> >>> for i in range(4): arr[i] = [0]*4
> ...
> >>> arr[1][2] = 42
> >>> arr
> [[0, 0, 0, 0], [0, 0, 42, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
> Yours, not feeling like working right now, -a.
OK. I'll call!
How about:
>>> arr = map( lambda x: [x]*4, [0]*4 )
>>> arr
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> arr[1][2] = 42
>>> arr
[[0, 0, 0, 0], [0, 0, 42, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>>
Unfortunately, this doesn't appear to recursively propagate to
higher dimensions. :-(
>>> XXX = map( lambda x: [x]*4, map( lambda x: [x]*4, [0]*4 ) )
>>> XXX[1][2][3] = 123
>>> XXX
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 123], [0,
0, 0, 123], [0, 0, 0, 123], [0, 0, 0, 123]], [[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, 0, 0, 0], [0, 0, 0, 0]]]
You mixed it up slightly. Try:
>>> XXX = map( lambda x: map (lambda x: [x]*4, [0]*4), [0]*4)
>>> XXX[1][2][3] = 123
>>> XXX
[[[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, 0, 0, 123], [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, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]]
Regards,
Greg