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

Chris Angelico rosuav at gmail.com
Sat Jun 16 08:04:20 EDT 2018


On Sat, Jun 16, 2018 at 9:09 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.

The nearest you'd get to "adding to a list/array" in C would be adding
to a pointer. But I don't see people writing code like this in Python:

>>> x = [10, 20, 30, 40]
>>> x += 1
>>> assert x == [20, 30, 40]

:)

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

Agreed, although I can't remember this ever coming up outside of
interactive work. When you do something at the interactive prompt, you
can kinda feel that it should "rollback" on exception, and yet some
part of it has happened. But in most scripts, that TypeError is going
to pull you all the way out of the scope where 't' exists -
frequently, it'll just straight-up terminate the script - so you won't
often see this.

ChrisA


More information about the Python-ideas mailing list