Multi-dimensional list initialization
andrew3 at r3dsolutions.com
Mon Nov 5 07:44:39 CET 2012
On 11/04/2012 10:27 PM, Demian Brecht wrote:
> So, here I was thinking "oh, this is a nice, easy way to initialize a 4D matrix" (running 2.7.3, non-core libs not allowed):
> m = [[None] * 4] * 4
> The way to get what I was after was:
> m = [[None] * 4, [None] * 4, [None] * 4, [None * 4]]
FYI: The behavior is the same in python 3.2
produces a nested list with all references being to the first instance
of the inner list construction.
I agree, the result is very counter-intuitive; hmmm... but I think you
m = [[None] * 4, [None] * 4, [None] * 4, [None] *4 ]
m = [[None] * 4, [None] * 4, [None] * 4, [None * 4]]
? :) ?
I asked a why question on another thread, and watched several dodges to
the main question; I'll be watching to see if you get anything other
than "That's the way it's defined in the API". IMHO -- that's not a
My guess is that the original implementation never considered anything
beyond a 1d list.
A more precise related question might be: is there a way to force the
replication operator to use copying rather than referencing?
More information about the Python-list