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

Steven D'Aprano steve at pearwood.info
Sat Jun 16 19:52:16 EDT 2018


On Sat, Jun 16, 2018 at 08:21:42PM +0300, Mikhail V wrote:

> For example, such code:
> 
>     L = []
>     L[] = x
>     L[] = y

Should be written as L = [x, y].

> imo has more chance to be understood correctly than e.g.:
> 
>     L = []
>     L ^= x
>     L ^= y

I disagree. The first syntax L[] = x looks so similar to L[:] assignment 
that I keep reading it as "set the list L to a single item x". It 
certainly doesn't look like an append operation.

The second at least looks like a mutation on L.

 
> By L[] there is some mnemonical hint because [] is used to create
> new empty list.

How is that a hint? What is the connection between "append an item" and 
"create a new empty list"?


> So if L[] is found somwhere far from initialisation - it may be a good aid.
> It makes it more clear what is happening, compared to augmented operator.

I don't think so.

Here is a radical thought... why don't we give lists a method that 
inserts items at the end of the list? We could call it something like 
"append", and then instead of hoping people guess what the syntax does, 
they can just look up the name of the method?

L.append(x)

might work.

*wink*





-- 
Steve


More information about the Python-ideas mailing list