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

Michael Selik mike at selik.org
Tue Jun 12 11:00:27 EDT 2018


That's a slice assignment, works great. I think if you use it more often
you'll start to enjoy it.

However, lists are optimized for append. Insert is slow. It should be
discouraged, not encouraged by the language. If inserting is just a tad
more awkward than appending, that's the language design giving you a hint
that you should do what reads beautifully.


On Tue, Jun 12, 2018, 7:54 AM Mikhail V <mikhailwas at gmail.com> wrote:

> I think it would be logical to have the insert operator for lists.
> Similar to list extend operator += , it could use one of augmented
> assignment operators, e,g, /=.
>
>     L = ["aa"]
>
>     L[0] /= "bb"
>
>     ->  ["bb", "aa"]
>
>     L[0] /= [1,2]
>
>     ->  [[1,2], "aa"]
>
> etc.
>
> Without index it would work like append():
>
>     L /= "bb"
>
>     #->  ["aa", "bb"]
>
>
> As for possible spellings I like this one as well:
>
>     L[i] ^= e
>
> The proposed solution is meant to have insert() method semantics,
> plus it would cover append() method nicely.
>
> Insert and append are very frequent operations, so I wonder
> if there was already related suggestion?   Is there some technical
> problem with implementing this?
>
>
> Note that there is a trick to 'insert' an element with slicing syntax,
> e.g.:
>
>     L[0:0] = [[1,2]]
>
>     -> [[1,2], "aa"]
>
>
>     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.
>
>
> M
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180612/f0d2b951/attachment.html>


More information about the Python-ideas mailing list