Python Reference ยท Lists, Tuples and Ranges
Python list.insert() method
Reference for Python list.insert(): put an item at a chosen index, how out-of-range and negative indexes behave, why it is slow at the front, and alternatives.
The insert() method places an item at a given position in a list. Everything from that position onward shifts one place to the right. It works in place and returns None.
Unlike indexing, insert() never raises IndexError: an index beyond the end simply appends, and one before the start inserts at the front.
letters = ["a", "c"] letters.insert(1, "b") print(letters) # ['a', 'b', 'c']
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.insert(index, item)
| Name | Description |
|---|---|
index |
Position where item should end up. 0 is the front; len(list) or more means the end. Negative values count from the end, and the item goes before that element. |
item |
Any object. |
Return value: None.
Raises: TypeError if index is not an integer.
Usage notes
- Never out of range. Large indexes append and very negative ones prepend. That is convenient, but it also hides off-by-one mistakes.
- Negative indexes insert before.
insert(-1, x)putsxbefore the last element, not after it. To append, useappend(). - One item. A list argument is inserted as a single nested element. To splice in several items, use slice assignment:
lst[i:i] = [a, b]. - Slow at the front. Every later element has to move, so
insert()is O(n). Inserting repeatedly at index 0 in a big list is a common performance trap; usecollections.deque.appendleft()or build in reverse and callreverse(). - Keeping a list sorted.
bisect.insort()finds the right index with a binary search and then inserts. The shifting cost remains. - Returns
None. Do not assign the result. - Index shifts. After inserting, indexes of later items increase by one. Take care if you also hold stored positions.
Related
list.append(),list.extend(),list.pop(),list.remove(),list.index(),list- Lessons: Lists, List methods, Slicing