[Python-ideas] Operator for inserting an element into a list

Steven D'Aprano steve at pearwood.info
Sat Jun 16 07:09:06 EDT 2018


On Sat, Jun 16, 2018 at 01:06:45PM +1200, Greg Ewing wrote:
> Michael Selik wrote:
> >The += operator was meant as an alias for ``x = x + 1``. The 
> >fact that it mutates a list is somewhat of a surprise.
> 
> That's very much a matter of opinion. For every person who
> thinks this is a surprise, you can find another that thinks
> it's obvious that += should mutate a list, and is surprised
> by the fact that it works on immutable types at all.

Given the ubiquity of += in C, where it works on numbers but not lists, 
and the general difficulty many people have in dealing with the 
difference between assignment and mutation, I think the ratio would be 
closer to 20:1 than 1:1.

But regardless, I'm pretty sure that nobody expects this:


py> t = ([], None)
py> t[0] += [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
py> print(t)
([1], None)


> surprised by at least one of its meanings. :-)
> 
> Maybe we should call it the "Spanish Inquisition operator".

:-)


-- 
Steve


More information about the Python-ideas mailing list