How to Insert Element at Specific Index in List in Python
Use the
list.insert(index, element) method to add an element at a specific position in a Python list. The index is where you want to insert, and element is the value to add.Syntax
The syntax to insert an element at a specific index in a list is:
list.insert(index, element)
Here, list is your list variable, index is the position where you want to insert the element, and element is the value you want to add.
The element is inserted before the current element at the given index.
python
list.insert(index, element)Example
This example shows how to insert the number 99 at index 2 in a list of numbers.
python
numbers = [10, 20, 30, 40] numbers.insert(2, 99) print(numbers)
Output
[10, 20, 99, 30, 40]
Common Pitfalls
Common mistakes when using insert() include:
- Using an index larger than the list length inserts the element at the end.
- Using a negative index counts from the end, which can be confusing.
- Trying to assign to an index directly (like
list[index] = element) replaces an element instead of inserting.
python
numbers = [1, 2, 3] # Wrong: replaces element at index 1 numbers[1] = 99 print(numbers) # Output: [1, 99, 3] # Right: inserts 99 at index 1 numbers.insert(1, 99) print(numbers) # Output: [1, 99, 99, 3]
Output
[1, 99, 3]
[1, 99, 99, 3]
Quick Reference
| Method | Description | Example |
|---|---|---|
| insert(index, element) | Insert element before index | list.insert(2, 'a') |
| append(element) | Add element at end | list.append('a') |
| extend(iterable) | Add multiple elements at end | list.extend([1, 2]) |
Key Takeaways
Use list.insert(index, element) to add an element at a specific position.
If index is larger than list length, element is added at the end.
Negative index counts from the end of the list.
Assigning to list[index] replaces an element, it does not insert.
insert() modifies the list in place and returns None.