Multi-dimensional list initialization

Andrew Robinson andrew3 at
Tue Nov 6 22:36:10 CET 2012

On 11/06/2012 01:19 AM, Ian Kelly wrote:
> On Tue, Nov 6, 2012 at 1:21 AM, Andrew Robinson
>> If you nest it another time;
>> [[[None]]]*4, the same would happen; all lists would be independent -- but
>> the objects which aren't lists would be refrenced-- not copied.
>> a=[[["alpha","beta"]]]*4 would yield:
>> a=[[['alpha', 'beta']], [['alpha', 'beta']], [['alpha', 'beta']], [['alpha',
>> 'beta']]]
>> and a[0][0]=1 would give [[1],[['alpha', 'beta']], [['alpha', 'beta']],
>> [['alpha', 'beta']]]]
>> rather than a=[[1], [1], [1], [1]]
>> Or at another level down: a[0][0][0]=1 would give: a=[[[1, 'beta']],
>> [['alpha', 'beta']], [['alpha', 'beta']], [['alpha', 'beta']] ]
>> rather than a=[[[1, 'beta']], [[1, 'beta']], [[1, 'beta']], [[1, 'beta']]]
> You wrote "shallow copy".  When the outer-level list is multiplied,
> the mid-level lists would be copied.  Because the copies are shallow,
> although the mid-level lists are copied, their contents are not.  Thus
> the inner-level lists would still be all referencing the same list.
> To demonstrate:
I meant all lists are shallow copied from the innermost level out.
Equivalently, it's a deep copy of list objects -- but a shallow copy of 
any list contents except other lists.

>>>> from copy import copy
>>>> class ShallowCopyList(list):
> ...     def __mul__(self, number):
> ...         new_list = ShallowCopyList()
> ...         for _ in range(number):
> ...             new_list.extend(map(copy, self))
> ...         return new_list
> ...
That type of copy is not equivalent to what I meant; It's a shallow copy 
only of non-list objects.
> This shows that assignments at the middle level are independent with a 
> shallow copy on multiplication, but assignments at the inner level are 
> not. In order to achieve the behavior you describe, a deep copy would 
> be needed. 
Yes, it can be considered a deep copy of *all* list objects -- but not 
of non list contents.
It's a terminology issue -- and you're right -- I need to be more precise.
>> That really is what people *generally* want.
>> If the entire list is meant to be read only -- the change would affect
>> *nothing* at all.
> The time and memory cost of the multiplication operation would become
> quadratic instead of linear.

Perhaps, but the copy would still not be _nearly_ as slow as a list 
comprehension !!!

Being super fast when no one uses the output -- is , "going nowhere fast."
I think It's  better to get at the right place at a medium speed than 
nowhere fast;

List comprehensions *do* get to the right place, but *quite* slowly.  
They are both quadratic, *and* multiple tokenized steps.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list