list.insert()
Puts a new item into a list at the position you choose, moving the items after it one place to the right.
list.insert(i, x)insert(i, x) places the item x so that it ends up at index i. Everything that was at that position or later moves one step to the right. Nothing is replaced.
Use it when order matters and the new item does not belong at the end: a new first item, a step in the middle of a recipe, a name in an already sorted list.
A position past the end never raises an error: the item simply goes at the end. Negative positions count from the end, but insert(-1, x) puts x before the last item, not after it.
Parameters
| Parameter | What it is |
|---|---|
irequired | The index the new item should have. 0 means the very front. Values larger than the length add at the end; negative values count from the end. |
xrequired | The item to insert. |
Return value
Nothing (None). The list is changed in place.
Examples
1Add an item at the front
queue = ["Ben", "Chloe"]
queue.insert(0, "Ana")
print(queue)['Ana', 'Ben', 'Chloe']
2Insert in the middle
steps = ["boil water", "add pasta", "serve"]
steps.insert(2, "drain")
for n, step in enumerate(steps, start=1):
print(n, step)1 boil water 2 add pasta 3 drain 4 serve
"drain" now has index 2, and "serve" moved from index 2 to index 3.
3Positions past the end and negative positions
nums = [10, 20, 30]
nums.insert(100, 40)
print(nums)
nums.insert(-1, 35)
print(nums)[10, 20, 30, 40] [10, 20, 30, 35, 40]
-1 means "before the current last item". To add at the end, use list.append().
4Keep a list sorted while adding
Find the first item that is bigger, and insert before it.
scores = [12, 18, 25, 40]
new = 21
pos = 0
while pos < len(scores) and scores[pos] < new:
pos += 1
scores.insert(pos, new)
print(scores)[12, 18, 21, 25, 40]
The bisect module does the same search for you: bisect.insort(scores, new).
Common mistakes
Swapping the two arguments
The position comes first, then the item. insert("x", 0) raises a TypeError, because a string is not a position.
letters = ["b", "c"]
letters.insert(0, "a")
print(letters)['a', 'b', 'c']
Using insert(-1, x) to add at the end
insert(-1, x) lands one place before the end. Use append(x) or insert(len(items), x) to really add at the end.
Questions people ask
How do I add an item at the beginning of a list in Python?
items.insert(0, value). If you do it very often on a long list, collections.deque and its appendleft() is much faster.
Does insert() replace the item at that position?
No. It pushes the old item one step right. To replace, assign: items[2] = value.
How do I insert several items at a position?
Use slice assignment: items[2:2] = ["x", "y"] puts both at index 2 and 3 without removing anything.