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

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Jun 12 19:15:07 EDT 2018


Mikhail V wrote:
>     L[0:0] = ["bb"]
> 
>     -> ["bb", "aa"]
> 
> The trick is to put brackets around the element and so it works as insert().
> Though additional brackets look really confusing for this purpose, so I don't
> feel like using this seriously.

I don't think it's all that confusing. It looks a bit cluttered
when the thing being inserted is itself a list literal, but
that seems like a rare case of something that's not all that
coommon in the first place.

My feeling is that inserting is not a frequent enough operation
to warrant having its own operator, especially not when there
is already a syntax that does the same thing.

> Is there some technical problem with implementing this?

Yes, it doesn't fit into the current scheme for augmented
assignment operators. There are no special methods for
combining augmented assignments with slicing -- you
couldn't implement this just by adding an __ixor__ method
to the list type.

There would need to be a new special method for "in-place
xor with  slice", and the compiler would have to recognise
this combination and emit special bytecode for it. That
would raise the question of why ^= is getting this
special treatment but not any of the other augmented
assignments, and why not "in-place operation with
attribute" as well, and potentially we would end up with
two new entire sets of special methods for different
flavours of augmented assignments.

I really don't think we want to go there.

-- 
Greg


More information about the Python-ideas mailing list