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

Terry Reedy tjreedy at udel.edu
Tue Jun 12 15:26:22 EDT 2018

On 6/12/2018 10:54 AM, Mikhail V 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, /=.


> Note that there is a trick to 'insert' an element with slicing syntax, e.g.:

This is not a 'trick'.  It is a particular case of a general operation: 
replacing a length m slice of a list with a sequence of length n.  Both 
m and n can be 0.  The replacement sequence can be any iterable.

 >>> l = [1,2,3]
 >>> l[0:0] = 'abc'
 >>> l
['a', 'b', 'c', 1, 2, 3]

>      L[0:0] = [[1,2]]
>      -> [[1,2], "aa"]
>      L[0:0] = ["bb"]
>      -> ["bb", "aa"]

In these examples, m and n are 0 and 1.

> The trick is to put brackets around the element and so it works as insert().

Again, not a trick.  Putting brackets around the element makes it 
sequence of length 1.  To possible be less confusing, you could use (,)

 >>> l[0:0] = ([1,2],)
 >>> l
[[1, 2], 'aa']

> Though additional brackets look really confusing for this purpose,
> so I don't feel like using this seriously.

Learning about lists means learning about slice assignment: replace a 
sublist with another sequence.

Terry Jan Reedy

More information about the Python-ideas mailing list