Python Glossary Русский

all Python 3Lists (list)function

list.insert

adding

Insert an item before the given index; index ≥ len appends, negative counts from the end.

Syntax

lst.insert(index, item)

Inserting shifts every element to the right, so it costs O(n): building a list with insert(0, x) in a loop degrades to O(n²) — use collections.deque when you need cheap inserts at the front. Out-of-range indices never raise IndexError: too large appends at the end, too negative inserts at position 0.

Examples

lst = [1, 2, 3]
lst.insert(1, 99)
print(lst)   # → [1, 99, 2, 3]
lst.insert(0, 'start')
print(lst)   # → ['start', 1, 99, 2, 3]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy