Lists in Python are mutable, which means items can be deleted or removed.
1. Remove a Specific Item with remove()
The remove() method deletes the first occurrence of a specified value.
fruits = ["apple", "banana", "cherry", "banana"] fruits.remove("banana") print(fruits) # Output: # ['apple', 'cherry', 'banana']If the value is not in the list, Python raises a ValueError.
2. Remove by Index with pop()
The pop() method deletes an item by index and returns it.
nums = [10, 20, 30, 40] removed = nums.pop(1) print(removed) print(nums) # Output: # 20 # [10, 30, 40]If no index is provided, pop() removes and returns the last item.
3. Delete with del
The del statement deletes an item by index without returning it.
colors = ["red", "blue", "green"] del colors[1] print(colors) # Output: # ['red', 'green']You can also delete multiple items using slicing:
nums = [1, 2, 3, 4, 5] del nums[1:4] print(nums) # Output: # [1, 5]4. Remove All Items with clear()
The clear() method deletes all elements, leaving an empty list
data = [1, 2, 3, 4] data.clear() print(data) # Output: # []5. Remove Items Using List Comprehension
List comprehensions can filter out unwanted items based on a condition
nums = [1, 2, 3, 4, 5, 6] nums = [x for x in nums if x % 2 == 0] print(nums) # Output: # [2, 4, 6] This removes all odd numbers from the list.
6. Remove Duplicates While Removing Items
You can remove duplicates and unwanted values together
vals = [2, 2, 3, 2, 4] clean = [] for x in vals: if x not in clean: clean.append(x) print(clean) # Output: # [2, 3, 4]Method Removes By Returns Value? Use Case remove(x) value ❌ No delete first matching item pop(i) index ✔ Yes when you need removed item pop() last item ✔ Yes stack-like behavior del index / slice ❌ No delete range or variable clear() entire list ❌ No empty list completely
Important Notes
-
remove()deletes by value;pop()anddeldelete by index. -
pop()returns the removed value;deldoes not. -
clear()empties the list but keeps the list object. -
Using list comprehension creates a new list.