2. Removal Methods in List
Python provides different methods to remove items from a list.
The most common are remove(), pop() and clear().
1. remove()
remove() deletes the first occurrence of the specified value from the
list.
numbers = [10, 20, 30, 20, 40]
numbers.remove(20)
print(numbers)
Output:
[10, 30, 20, 40]
Explanation:
remove(20)searches for the value 20 in the list.- It removes the first occurrence of 20 it finds from left to right.
- List still has another 20 left at a later position.
- If the value is not present in the list, it raises a
ValueError.
2. pop()
pop() removes the item at a given index. If no index is given, it removes the
last item.
numbers = [10, 20, 30, 40]
numbers.pop(2)
print(numbers)
Output:
[10, 20, 40]
Explanation:
pop(2)removes the element at index 2, which is30.- List becomes [10, 20, 40].
The following example shows how pop() behaves when no index is given:
numbers = [10, 20, 30]
numbers.pop()
print(numbers)
Output:
[10, 20]
Explanation:
pop()removes the last element from the list when no index is given.- In the example, the last element is 30, so it gets removed.
- The updated list becomes
[10, 20].
3. clear()
clear() removes all elements from the list, making it empty.
numbers = [10, 20, 30]
numbers.clear()
print(numbers)
Output:
[]
Explanation:
- After
clear(), the list becomes an empty list:[].
Summary:
remove(value)deletes the first matching value.pop(index)deletes by position; default is last item.clear()removes everything, list becomes empty.