Multi-dimensional list initialization

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Nov 6 02:32:09 CET 2012


On 5 November 2012 09:13, Hans Mulder <hansmu at xs4all.nl> wrote:
> On 5/11/12 07:27:52, 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]]
>
> Or alternateively:
>
> m = [[None] * 4 for _ in range(4)]

That's the way to do it.

I've seen this question many times between here and the python-tutor
list. It does seem to be a common gotcha.

I was just thinking to myself that it would be a hard thing to change
because the list would need to know how to instantiate copies of all
the different types of the elements in the list. Then I realised it
doesn't. It is simply a case of how the list multiplication operator
is implemented and whether it chooses to use a reference to the same
list or make a copy of that list. Since all of this is implemented
within the same list type it is a relatively easy change to make
(ignoring backward compatibility concerns).

I don't see this non-copying list multiplication behaviour as
contradictory but has anyone ever actually found a use for it?


Oscar


More information about the Python-list mailing list