Python Remove List Items
Python offers several removal tools depending on whether you know the item's value, its position, or want to clear the list entirely.
Removing by value with remove()
The remove() method deletes the first item that matches the value you pass. If the same value appears more than once, only the earliest occurrence is taken out, and if the value is not present at all, Python raises a ValueError.
remove() by value
cart = ["pen", "book", "pen", "eraser"]
cart.remove("pen")
print(cart)The result is ['book', 'pen', 'eraser']. Only the first 'pen' was removed; the second one remains because remove() stops after the first match.
Removing by position with pop() and del
The pop() method removes the item at a given index and returns it, which is useful when you need the removed value. Calling pop() with no argument removes and returns the last item. The del keyword also deletes by index but does not return anything.
pop() and del
queue = ["a", "b", "c", "d"]
first = queue.pop(0)
del queue[0]
print(first, queue)queue.pop(0) removes 'a' and stores it in first, leaving ['b', 'c', 'd']. Then del queue[0] deletes 'b', so the final output is: a ['c', 'd'].
Emptying the list with clear()
clear() removes everything
items = [1, 2, 3]
items.clear()
print(items)clear() empties the list in place, leaving []. The variable still points to the same list object, but it now contains no items.