🎓 A1Learner
🔍

Python Remove Set Items

Removing a set item takes that item out of the set.

Remove a known item

Use remove() when you know the item is there.

guests = {"Ana", "Ben", "Cy", "Dee"}
guests.remove("Ben")
print(sorted(guests))

Discard a maybe item

Discard stays quiet if the item is missing.

guests = {"Ana", "Ben"}
guests.discard("Zed")
print(sorted(guests))

Pop one item

Pop removes one arbitrary item and returns it. This set has one item, so the choice is fixed here.

solo = {"Ana"}
item = solo.pop()
print(item)
print(len(solo))

Clear the set

Clear removes every item from the set.

guests = {"Ana", "Ben"}
guests.clear()
print(len(guests))

Example

guests = {"Ana", "Ben", "Cy", "Dee", "Eli"}
guests.remove("Ben")
guests.discard("Zed")
guests.discard("Cy")
print(sorted(guests))
guests.clear()
print(len(guests))

Key points

  • Use remove() to remove an item you know is present
  • Use discard() to remove an item that may be missing
  • A removed item is no longer in the set.
  • Use pop() to remove and return one arbitrary item
  • Use clear() to empty a set but keep the set
  • Use del to delete the whole set variable

In this example, guests starts with five names. The remove() call removes Ben, who is present. The first discard() call tries Zed, who is missing. It stays quiet and changes nothing. The second discard() call removes Cy. The print shows the three guests left. The clear() call then empties the set.

Note

remove() raises KeyError if the item is missing — use discard() when you are unsure

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A name may or may not be in a set. Which method removes it without an error if it is missing?