set.remove()
Deletes an element from a set. Raises KeyError if the element is not in the set; use discard() to skip that check.
set.remove(elem)remove(x) takes the element x out of the set. Since a set holds each value only once, there is nothing like "the first match": the element is either there and removed, or not there.
If it is not there, remove() raises a KeyError. That is useful when a missing element means something went wrong. When a missing element is normal, use set.discard(), which does the same job silently.
Removing is very fast in a set, whatever its size, which is one reason to use a set instead of a list for a big collection you check and remove from often.
Parameters
| Parameter | What it is |
|---|---|
elemrequired | The element to remove. |
Return value
Nothing (None). The set is changed in place.
Examples
1Remove an element
seats = {1, 2, 3, 4}
seats.remove(3)
print(seats){1, 2, 4}2Book seats until none are free
free = {1, 2, 3}
for wanted in [2, 3]:
free.remove(wanted)
print("Booked seat", wanted, "- free:", sorted(free))Booked seat 2 - free: [1, 3] Booked seat 3 - free: [1]
3remove() vs discard()
tags = {"news", "sport"}
tags.discard("music")
print(sorted(tags))
try:
tags.remove("music")
except KeyError:
print("KeyError: music is not in the set")['news', 'sport'] KeyError: music is not in the set
4Tick off tasks
todo = {"wash", "cook", "shop"}
for done in ["cook", "shop"]:
if done in todo:
todo.remove(done)
print("Left:", sorted(todo))Left: ['wash']
Common mistakes
Removing something that is not there
This raises KeyError. Check with in, or use discard().
ids = {10, 20}
if 30 in ids:
ids.remove(30)
else:
print("30 was not in the set")
ids.discard(30)
print(sorted(ids))30 was not in the set [10, 20]
Removing while looping over the same set
Changing a set's size during a loop over it raises RuntimeError. Loop over a copy, or build a new set with a comprehension.
nums = {1, 2, 3, 4, 5, 6}
evens = {n for n in nums if n % 2 == 0}
nums -= evens
print(sorted(nums))[1, 3, 5]
Questions people ask
What is the difference between remove() and discard() in a set?
Both delete an element. remove() raises KeyError if it is missing; set.discard() does nothing in that case.
How do I remove several elements from a set?
Subtract them: s -= {1, 2}, or call set.difference() for a new set.
How do I remove and get any element?
Use set.pop(). It returns the element it removed, but you cannot choose which one.