Removing by Value: remove()
The method pop() removes an element by its position. Often, though, you know what you want to remove, not where it is. For that, lists have the method remove(): you write a value in the parentheses, and it removes the element with that value:
guests = ["Anna", "Tom", "Lucy", "Max"]
guests.remove("Tom")
print(guests)This prints:
['Anna', 'Lucy', 'Max']If the value is in the list more than once, remove() removes only the first one, counted from the start:
numbers = [3, 7, 3, 9]
numbers.remove(3)
print(numbers)This prints:
[7, 3, 9]Unlike pop(), remove() doesn't return the removed element. You already know its value, after all.
If the value isn't in the list at all, the program stops with an error. Text is compared exactly, so "tom" with a lowercase t isn't the same as "Tom":
guests = ["Anna", "Tom", "Lucy"]
guests.remove("tom")The program ends with this error:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
ValueError: list.remove(x): x not in listValueError is an error with a value. Here, x stands for the value you wanted to remove, and not in list says that it isn't in the list. In the next exercise, you'll learn how to check first whether a value is in a list.
Instructions
The weather forecast says it won't rain. Remove "umbrella" from the list packing with remove().
Print packing. The output should be ['passport', 'sunscreen', 'sunglasses'].
Start programming for free
8/12