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

Mikhail V mikhailwas at gmail.com
Tue Jun 12 14:08:22 EDT 2018


On Tue, Jun 12, 2018 at 7:42 PM, Clint Hepner <clint.hepner at gmail.com> wrote:
>
>> On 2018 Jun 12 , at 10:54 a, 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"]
>
> -1. There's not much about this that is logical, no matter how much
> you want an insertion operator. Even if L[0] /= "bb" worked, then logically
> so should L[0] = L[0] / "bb". However, there is no sense in which L[0] / "bb"
> by itself has any meaning, and what would L[1] = L[0] / "bb" mean?
>
> And finally, L[0] /= x (and really, every other augmented operator) *already has* a meaning:
>

Hi Clint, (and others),
I must say it is misunderstanding due to my false examples,
that I have pasted in original post (I had 2 cloned texts in my text editor
and copied the wrong one). I have posted correction just 10 minutes after
the original post, see last post.
Sorry for confusion!

So the idea was about an insert/append operator.
Which would use augmented operator. The operator may be
/= or ^=. (I like ^= more, so I'll put here example with it).

    L = [1,2,3]

    L[0:0] ^= 0

-> [0,1,2,3]

    L[0:0] ^= -1

->  [-1, 0, 1, 2, 3]

    L ^= 4   (without index, it works as append() )

->  [-1, 0, 1, 2, 3, 4]


As for your question, what would:

     List1[a:b] = List1[c:d] ^ var

mean?  (is that what you have asked?)

Well, I think this would mean simply :
- first append var to List1[c:d] ,
- then replace the List1[a:b] part with the result.

So at least L ^= 4 would make sense as  L = L ^ 4.


Actually current semantics of += for lists:

L += var

and

L = L + var

are different, so it seems to me they were not meant to be
bound together.



>> Note that there is a trick to 'insert' an element with slicing syntax, e.g.:
>>
>>    L[0:0] = [[1,2]]
>>
>>    -> [[1,2], "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.
>
> It's no more confusing than co-opting an unrelated operator to do the same thing.


If the intention is to insert an element, indeed it is confusing, for
me at least:

    L[0:0] = "bb"

-> ["b","b","aa"]


More information about the Python-ideas mailing list