Python 3 reference · List Methods
Python List insert() Method
Insert an item at a given position, shifting later items to the right. Index 0 adds to the front.
Python 3 Since 3.0
Syntax
list.insert(index, item)
Parameters
| Parameter | Description |
|---|---|
index |
Position to insert before; past the end appends, negative counts from the end. |
item |
The value. |
Return value
None.
Examples
queue = ["b", "c"]
queue.insert(0, "a")
queue.insert(len(queue), "d")
print(queue)
Output
['a', 'b', 'c', 'd']
from collections import deque
q = deque(["b", "c"])
q.appendleft("a") # fast for adding to the front
print(list(q))
Output
['a', 'b', 'c']
Inserting near the front of a long list is slow (every later item moves). For queues, use collections.deque.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
list.append()· Add one item to the end of a list, changing the list in place. Returns None.list.pop()· Remove and return the item at a position, the last item by default. Raises IndexError on an empty list.list.extend()· Add every item from an iterable to the end of the list, in place. Like append() for many items at once.- Python Lists · tutorial