Remove List Items
Removal Methods
Python lists provide several ways to remove elements:
- **remove(value)**: Removes the first matching element
- **pop([index])**: Removes and returns the element at the given index (defaults to the last)
- **del statement**: Deletes elements by index or slice
- **clear()**: Empties the entire list
- **List comprehension**: Creates a filtered list without certain elements
Example
colors = ['red', 'green', 'blue', 'yellow', 'green']
# Remove by value
colors.remove('green') # Removes the first 'green'
# Remove by index
popped = colors.pop(1) # Removes 'blue'
# Delete slice
del colors[0:1] # Removes 'red'
# Clear all
colors.clear()
print(colors)
Output
[]
Performance Considerations
Method | Time Complexity | Best For |
---|---|---|
remove() | O(n) | Deleting by value |
pop() | O(1) at end, O(n) elsewhere | When you need the removed element |
del slice | O(n) | Bulk removal of ranges |
clear() | O(1) | Resetting a list quickly |
List comprehension | O(n) | Conditional filtering |
Advanced Removal Patterns
For more control, combine removal methods with loops, comprehensions, or slicing.
Example
# Remove all occurrences of a value
numbers = [1, 2, 3, 2, 4, 2, 5]
while 2 in numbers:
numbers.remove(2)
print(numbers) # [1, 3, 4, 5]
# Use list comprehension to filter
primes = [x for x in numbers if x in {2, 3, 5, 7}]
print(primes) # [3, 5]
# Slice assignment for bulk removal
lst = [1, 2, 3, 4, 5]
lst[1:4] = [] # Removes indices 1-3
print(lst) # [1, 5]
Output
[1, 3, 4, 5] [3, 5] [1, 5]