List replication operator
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 25 20:42:32 EDT 2018
On Fri, 25 May 2018 09:58:19 -0700, Rob Gaddi wrote:
[...]
>> This is a frequent, recurring pain point. Experienced programmers
>> forget how confusing the behaviour of * is because they're so used to
>> the execution model. They forget that writing a list comp is not even
>> close to obvious, not only for beginners but even some experienced
>> Python programmers.
>>
>>
> I agree that it's non-obvious, but I disagree with your diagnosis. The
> non-obvious bit is that the empty list is a reference to a newly created
> mutable, not an immutable constant. Or, more the point, that the word
> "mutable" is one that you need to know and think about in the first
> place.
I challenge you to read this bug report and claim that the poster's error
was to *correctly* think that [[]]*5 made five references to the same
list, but *incorrectly* failed to realise that list.append modified the
list in place.
https://bugs.python.org/issue33636
> class list(_list):
> @staticmethod
> def replicate(*n, fill=_nodefault, call=list):
> """Return a list of specified dimensions.
[...]
Interesting implementation to play with, thanks.
--
Steve
More information about the Python-list
mailing list