Multi-dimensional list initialization
Andrew Robinson
andrew3 at r3dsolutions.com
Mon Nov 5 01:44:39 EST 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
m=[[None]*4]*4
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
meant:
m = [[None] * 4, [None] * 4, [None] * 4, [None] *4 ]
rather than:
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
real answer.
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
mailing list