Multi-dimensional list initialization

Joshua Landau joshua.landau.ws at gmail.com
Wed Nov 7 23:16:23 CET 2012


*Spoiler:* You've convinced me.

On 7 November 2012 14:00, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:

> 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']
>

I see. I agree that that is a valid point. Remember, though, that we could
just keep this behaviour:

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


> If you use this kind of multiplication what happens to the other
> cases? e.g. what do you give for:
>
> >>> [0] * [2, 3]
>

Nothing. If you allowed lists to multiply this time, why not with your
suggestion? We should require a tuple and a list.


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

Same.


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

== [0] * (2, 3)


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

Nothing.


> 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.
>

Agreed


> 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.


How is that a problem? They just wont get the functionality.


That said, losing:
[0] * (2, 3) == [0] * [2, 3]
would mean losing duck-typing in general. *Thus*, I fully agree with your
choice of exponentiation.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121107/cf63169b/attachment.html>


More information about the Python-list mailing list