[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

List replication operator

On 24May2018 18:17, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>Python has a sequence replication operator:
>py> [1, 2]*3
>[1, 2, 1, 2, 1, 2]
>Unfortunately, it is prone to a common "gotcha":
>py> x = [[]]*5  # make a multi-dimensional list
>py> x
>[[], [], [], [], []]
>py> x[0].append(1)
>py> x
>[[1], [1], [1], [1], [1]]
>The reason for this behaviour is that * does not copy the original list's
>items, it simply replicates the references to the items. So we end up
>with a new list containing five references to the same inner list.
>This is not a bug and changing the behaviour is not an option.
>But what do people think about proposing a new list replication with copy
>    [[]]**5
>would return a new list consisting of five shallow copies of the inner

I think I'm against it.

Shallow copies are just as easy to get wrong, for much the same reason that * 
can produce a surprise.

So to me this introduces a new operator without much benefit, and possibly 
negative side effects (bcause it makes makes choosing an approach to sequence 
replication harder: which form should I use, per case)? The * is faster while 
the ** is safer... in very limited contexts.

I would rather there were just one model of this replication, and the model we 
have is simple and direct, with exactly the same pitfalls and benefits as 
Python's function parameter default values. So people already need this issue 
in mind to work in the language.

I'm also against the "**" spelling I find, for much the same reasons that 
people oppose allowing "=" and "==" in the same syntactic location: they're 
easy to get wrong through typing inaccuracy.

Cameron Simpson <cs at cskk.id.au>