What is the difference between remove(), pop() and del for a list?
remove(x) deletes the first item equal to x. pop(i) deletes the item at index i (default last) and returns it. del lst[i] or del lst[a:b] deletes by index or slice and returns nothing.
Explain it simply
Think of a train reservation chart. remove says "cancel the first passenger named Ravi". pop says "cancel the passenger on seat 3 and hand me the ticket". del says "strike out seat 3" or a whole block of seats, with nothing handed back.
Example
nums = [10, 20, 30, 20, 40]
nums.remove(20)
print(nums) # Output: [10, 30, 20, 40]
last = nums.pop()
print(last, nums) # Output: 40 [10, 30, 20]
first = nums.pop(0)
print(first) # Output: 10
del nums[0]
print(nums) # Output: [20]
try:
nums.remove(99)
except ValueError:
print("not found") # Output: not foundWhat to say in the interview
"remove works by value and removes only the first match, raising ValueError if missing. pop works by index, returns the removed item, and defaults to the last one, raising IndexError on an empty list. del works by index or slice and returns nothing. pop() from the end is O(1); the others shift elements and are O(n)."
Common mistakes
- Expecting
removeto delete every occurrence. - Removing items from a list while looping over it.