list.insert()
Python · Lists
Theory
.insert(index, item) puts item into the list so that it ends up at position index, shifting the item that was there, and everything after it, one place to the right. sales = [100, 250, 300] then sales.insert(1, 999) gives [100, 999, 250, 300]. Like other list methods it changes the list in place and returns None.
Out-of-range indexes do not raise errors: an index of len(list) or larger appends at the end, and a very negative index inserts at the front. Negative indexes count from the end, but insert(-1, x) places x before the current last item, not after it. Because every later reference must move, insert() costs O(n): cheap at the end, expensive at index 0 for a long list. If you repeatedly add to the front, collections.deque with appendleft() is built for that.
Why we use it
Sometimes order matters and the new item belongs in the middle: a priority entry at the top, a header row at index 0, or a value placed into an already sorted list. insert() puts it exactly where you say.
When to use it
Use insert() for occasional placement at a specific position. Use append() for adding at the end, which is faster. For many front insertions use collections.deque, and to keep a list sorted as you insert use the bisect module.
How it works
- Call sales.insert(1, 999)
- Is the index beyond the end? Yes: Treat it as an append at the end. No: Use the given position.
- Shift every item from that position one slot to the right
- Write 999 into the freed slot
- print(sales) shows [100, 999, 250, 300]
Syntax
list.insert(index, item)Example
sales = [100, 250, 300]
sales.insert(1, 999)
print(sales)Key points
- index 0 inserts at the very beginning
- An index past the end simply appends; no IndexError
- insert(-1, x) puts x before the last item, not after it
- Slower than append() for large lists since items must shift (O(n))
- Returns None; the list is changed in place