Set method

set.remove()

Deletes an element from a set. Raises KeyError if the element is not in the set; use discard() to skip that check.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
elem
required
The element to remove.

Return value

Nothing (None). The set is changed in place.

Examples

1Remove an element

Pythoneditable
seats = {1, 2, 3, 4}
seats.remove(3)
print(seats)
Output
{1, 2, 4}

2Book seats until none are free

Pythoneditable
free = {1, 2, 3}
for wanted in [2, 3]:
    free.remove(wanted)
    print("Booked seat", wanted, "- free:", sorted(free))
Output
Booked seat 2 - free: [1, 3]
Booked seat 3 - free: [1]

3remove() vs discard()

Pythoneditable
tags = {"news", "sport"}
tags.discard("music")
print(sorted(tags))
try:
    tags.remove("music")
except KeyError:
    print("KeyError: music is not in the set")
Output
['news', 'sport']
KeyError: music is not in the set

4Tick off tasks

Pythoneditable
todo = {"wash", "cook", "shop"}
for done in ["cook", "shop"]:
    if done in todo:
        todo.remove(done)
print("Left:", sorted(todo))
Output
Left: ['wash']

Common mistakes

Removing something that is not there

This raises KeyError. Check with in, or use discard().

Pythoneditable
ids = {10, 20}
if 30 in ids:
    ids.remove(30)
else:
    print("30 was not in the set")
ids.discard(30)
print(sorted(ids))
Output
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.

Pythoneditable
nums = {1, 2, 3, 4, 5, 6}
evens = {n for n in nums if n % 2 == 0}
nums -= evens
print(sorted(nums))
Output
[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.

Spotted a mistake on this page? Tell us