Multi-dimensional list initialization

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Nov 7 15:00:27 CET 2012


On 7 November 2012 13:39, Joshua Landau <joshua.landau.ws at gmail.com> wrote:
>
> On 7 November 2012 11:11, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>>
>> A more modest addition for the limited case described in this thread could
>> be to use exponentiation:
>>
>> >>> [0] ** (2, 3)
>> [[0, 0, 0], [0, 0, 0]]
>
> Hold on: why not just use multiplication?
>
>>>> [0] * (2, 3)
>
> is an error now, and it makes total sense. Additionally, it's not breaking
> the "no copy -- _ever_" rule because none of the lists existed before. The
> values inside the list would be by reference, as before, so lst * (x,) would
> be the same as lst * x if x is an integer.

The problem is that this operation is asymmetric. Currently int/list
multiplication is commutative so that:

['a', 'b'] * 2 == 2 * ['a', 'b']

If you use this kind of multiplication what happens to the other
cases? e.g. what do you give for:

>>> [0] * [2, 3]

>>> [2, 3] * [0]

>>> (2, 3) * [0]

>>> (2, 3) * (4, 5)

and so on. Although Python does not guarantee commutativity of
multiplication in general I think that since for lists it has always
been commutative it would be bad to change that.

Exponentiation is expected to be asymmetric and is currently unused so
there is no ambiguity. The problem is if someone has already
subclassed list and added an exponentiation method.


Oscar


More information about the Python-list mailing list