How to Remove Element by Index from List in Python
To remove an element by index from a list in Python, use the
pop(index) method which removes and returns the element at the given index. Alternatively, use the del statement to delete the element at that index without returning it.Syntax
There are two main ways to remove an element by index from a list:
list.pop(index): Removes and returns the element atindex. If no index is given, it removes the last element.del list[index]: Deletes the element atindexwithout returning it.
python
my_list.pop(index)
del my_list[index]Example
This example shows how to remove elements by index using both pop() and del. It prints the list before and after removal.
python
my_list = ['apple', 'banana', 'cherry', 'date'] # Remove element at index 1 using pop removed = my_list.pop(1) print(f"Removed element: {removed}") print(f"List after pop: {my_list}") # Remove element at index 2 using del del my_list[2] print(f"List after del: {my_list}")
Output
Removed element: banana
List after pop: ['apple', 'cherry', 'date']
List after del: ['apple', 'cherry']
Common Pitfalls
Common mistakes include:
- Using an index that is out of range, which causes an
IndexError. - Confusing
pop()withremove().pop()removes by index,remove()removes by value. - Expecting
delto return the removed element; it does not.
python
my_list = [10, 20, 30] # Wrong: Index out of range # my_list.pop(5) # Raises IndexError # Correct: Check length before popping if len(my_list) > 2: removed = my_list.pop(2) print(f"Removed: {removed}")
Output
Removed: 30
Quick Reference
| Method | Description | Returns Removed Element? |
|---|---|---|
| list.pop(index) | Removes and returns element at index | Yes |
| del list[index] | Deletes element at index without returning | No |
Key Takeaways
Use list.pop(index) to remove and get the element at a specific index.
Use del list[index] to remove an element without returning it.
Avoid IndexError by ensuring the index exists in the list before removing.
pop() removes by index; remove() removes by value—do not confuse them.
del does not return the removed element, unlike pop.