Multi-dimensional list initialization

Oscar Benjamin oscar.j.benjamin at
Tue Nov 6 03:30:00 CET 2012

On 6 November 2012 02:01, Chris Angelico <rosuav at> wrote:
> On Tue, Nov 6, 2012 at 12:32 PM, Oscar Benjamin
> <oscar.j.benjamin at> wrote:
>> 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?
> Stupid example of why it can't copy:
> bad = [open("test_file")] * 4
> How do you clone something that isn't Plain Old Data? Ultimately,
> that's where the problem comes from. It's easy enough to clone
> something that's all scalars (strings, integers, None, etc) and
> non-recursive lists/dicts of scalars, but anything more complicated
> than that is rather harder.

That's not what I meant. But now you've made me realise that I was
wrong about what I did mean. In the case of

   stuff = [[obj] * n] * m

I thought that the multiplication of the inner list ([obj] * n) by m
could create a new list of lists using copies. On closer inspection I
see that the list being multiplied is in fact [[obj] * n] and that
this list can only know that it is a list of lists by inspecting its
element(s) which makes things more complicated.

I retract my claim that this change would be easy to implement.


More information about the Python-list mailing list