PythonPython ListsPython list insertion
How do you insert an element at a specific position?
Question 82 of 88 · Updated
On this page
Use items.insert(index, item) to add an item before the specified index. Existing elements shift to the right instead of being replaced. The original list changes, and the method returns None.
Example: Update a daily schedule#
PYTHONschedule = ['Breakfast', 'Lunch', 'Dinner'] schedule.insert(1, 'Snack') print(schedule) # ['Breakfast', 'Snack', 'Lunch', 'Dinner']
Snack takes index 1, and Lunch moves from index 1 to index 2.
Where does the item go?#
Each example starts with items = ['A', 'B', 'C'].
| Operation | Result |
|---|---|
items.insert(0, 'X') | ['X', 'A', 'B', 'C'] |
items.insert(2, 'X') | ['A', 'B', 'X', 'C'] |
items.insert(-1, 'X') | ['A', 'B', 'X', 'C'] |
items.insert(99, 'X') | ['A', 'B', 'C', 'X'] |
items.insert(-99, 'X') | ['X', 'A', 'B', 'C'] |
Negative indexes count from the end. Unlike ordinary indexing, insertion positions outside the list are clipped to the beginning or end.
Insert vs replace vs append#
- Use
insert(i, value)to add an item before position i. - Use
items[i] = valueto replace an existing item. - Use
append(value)when you only need to add an item at the end.
Common mistakes#
Do not assign the return value of insert() back to the list: it returns None. Supply an integer index, not a floating-point number. Like append(), insert() adds one object, even when that object is another list.
Interview takeaway: In CPython, inserting near the beginning or middle takes O(n) time in the worst case because existing references must shift. For adding at the end, append() is usually the clearer choice.
Official references#
References
- 1.Python Tutorial — More on Listsdocs.python.org
- 2.Mutable sequence typesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design