List replication operator

Chris Angelico rosuav at gmail.com
Fri May 25 04:06:00 EDT 2018


On Fri, May 25, 2018 at 5:50 PM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Peter Otten schrieb am 25.05.2018 um 09:28:
>> Steven D'Aprano wrote:
>>
>>> But what do people think about proposing a new list replication with copy
>>> operator?
>>>
>>>     [[]]**5
>>>
>>> would return a new list consisting of five shallow copies of the inner
>>> list.
>>
>> Yet another arcanum to learn for beginners with little return.
>> If you cannot refrain from tinkering with the language at least concentrate
>> on the features with broad application.
>> Thank you.
>
> I might have phrased this a little less ... short, but if it's really just
> about avoiding a call to "copy.deepcopy()" in certain special cases at the
> cost of adding new syntax, then I have to agree that we'd better avoid
> adding the syntax instead.
>

But the desire is to create a simple and obvious way to construct
lists of lists. Do a survey of moderately-skilled programmers in
various languages: "How would you create an array of five empty
arrays?" Will any of them reach for copy.deepcopy() or equivalent? I
doubt it. Most likely you'll get explicit loops. In Python, you'll
probably get a mixture of explicit loops, list comps, and the flawed
"[[]]*5". That's what this is being compared to.

I'm +0.25 on this. I wouldn't personally use it very often, but it
doesn't much hurt to have it. Downside: while it's all very well to
say that this is equivalent to copy.deepcopy(), that would imply
replicating copy.deepcopy's semantics in the core list type (unless
it's actually literally defined as importing a module and calling a
function), and deepcopy is a complicated function. I don't want to
have to debug issues where ([x]@2)[1] is semantically different from
copy.deepcopy(x) after some sort of upgrade.

ChrisA



More information about the Python-list mailing list