Python list insert method

table of Contents

description

Syntax and parameters

return value

Usage example

Insert before the specified position

Precautions

The inserted index exceeds the length of the list

Index value is not an integer


 

description

The Python list insert() method can insert elements into any position of the list. You can tell the insert() method where you want to insert through the offset, and the insert method will insert the element before the corresponding element at the index.

 

Syntax and parameters

list.insert(index, element)
name meaning Remarks
index Index of the position to be inserted Integer parameters that cannot be omitted
element Element to be inserted Parameters that cannot be omitted

 

return value

None. That is, the list.insert() method has no return value, and it acts on the list itself.

 

Usage example

Insert before the specified position

The insert() method is to insert the element before the corresponding element of the index. For example, the corresponding list:

a b c 12 qwe 233

 

Now call list.insert(3, d), the insert() method inserts element d before element 12 corresponding to the third index, that is:

a b c d 12 qwe 233

 

Code demo:

>>> demo = ["a", "b", "c", 12, "qwe", 233]
>>> demo.insert(3, "d")
>>> demo
['a', 'b', 'c', 'd', 12, 'qwe', 233]

But don't understand it as inserting the element into the specified index. For example, when the index parameter is negative:

>>> demo = [1, 2, 3]
>>> demo.insert(-1, 4)
>>> demo
[1, 2, 4, 3]

The insert method inserts element 4 in front of element 3 corresponding to the first index from the bottom of the list, instead of inserting element 4 into the position with index value -1.

 

Precautions

The inserted index exceeds the length of the list

When the index value exceeds the valid range of the list length, the insert() method does not throw an exception, but inserts the element at both ends of the list: if the index value is a positive integer, the element is inserted at the end of the list, in this case The insert() method has the same effect as the append() method; if the index value is a negative integer, the element is inserted at the head of the list.

>>> demo = ["Python", "C"]
>>> demo.insert(2, "Java")
>>> demo
['Python', 'C', 'Java']
>>> demo.insert(-4, "HTML")
>>> demo
['HTML', 'Python', 'C', 'Java']

 

Index value is not an integer

When the inserted index value is not an integer, the insert() method throws a TypeError exception.

>>> demo.insert(3.3, "MySQL")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: integer argument expected, got float

 

Guess you like

Origin blog.csdn.net/TCatTime/article/details/106456737
Recommended