Removing Elements from Sets
Concepts covered: Sets
A set has 4 methods that take values out. remove and discard each take out 1 named value and differ only in what happens when it is absent. pop takes out some member and hands it back. clear empties the set. To check what's there before or after, use in and not in.
remove raises, discard forgives
cart = {3, 5, 7}
cart.remove(5)
print(cart)
cart.discard(5)
print(cart)
cart.discard(99)
print(cart)Output:
{3, 7}
{3, 7}
{3, 7}remove(5) found 5 and took it out. discard(5) then looked for 5 and returned without complaint when it wasn't there. discard(99) did the same. Swap that last discard for remove and the program stops.
cart = {3, 7}
cart.remove(5)A KeyError names the value that was missing, the same error a dictionary raises for a missing key, because a set is stored much like a dictionary that has keys and no values. Use remove when absence means something went wrong upstream and you want the program to stop and say so. Use discard when absence is an ordinary state, such as cancelling a reservation that was already cancelled.
Testing before and after
online = {"ana", "raj", "li"}
online.remove("raj")
print("raj" in online)
print("ana" in online, "li" in online)
print(len(online))Output:
False True True 2
A removal shows up in 2 places: the removed value now fails the in test, and len drops by 1. Nothing else moves, because nothing in a set has a position to shift.
Guarding with in
blocked = {"spam", "scam"}
word = "spam"
if word in blocked:
blocked.remove(word)
print(len(blocked))
print("spam" not in blocked)Output:
1 True
The if word in blocked guard makes remove safe, which is what discard does on its own. Write the guard when the other branch has work of its own, such as printing a message; otherwise discard says the same thing in 1 line.
A loop of discard calls handles a batch of removals where some may not apply. Here 3 guests cancel, and 1 of them was never on the list.
guests = {11, 12, 13, 14}
cancelled = [12, 15, 13]
for guest in cancelled:
guests.discard(guest)
print("Still coming:", guests)
print("Seats needed:", len(guests))Still coming: {11, 14}
Seats needed: 2
Guest 15 was not in the set, and discard passed over it without raising anything. The set keeps 2 guests, and the seat count follows from len.
pop takes something, clear takes everything
pop removes 1 member and returns it, but you don't choose which. The set picks from its storage layout, so on a set with several members, treat the result as 'some member', never 'the first one' or 'the smallest'. Calling pop on an empty set raises KeyError. clear removes every member and leaves set().
tasks = {4}
done = tasks.pop()
print(done)
print(len(tasks))
tasks.update([1, 2, 3])
tasks.clear()
print(tasks)Output:
4 0 set()
With 1 member there is nothing to guess: pop returns 4. After clear, printing shows set(), the spelling for an empty set, since {} would read as an empty dictionary.
| Call | Effect | If the value is absent |
|---|---|---|
| `s.remove(x)` | Takes x out | `KeyError` |
| `s.discard(x)` | Takes x out | Nothing happens |
| `s.pop()` | Takes out some member and returns it | `KeyError` only when the set is empty |
| `s.clear()` | Takes out every member | Nothing to take, no error |
| `x in s` | Reports presence | Returns `False` |
- Do
- Use discard for batches where some values may already be gone
- Use remove when a missing value signals a bug worth stopping for
- Test with in when the other branch has its own work to do
- Avoid
- Treat pop as returning the first or smallest member
- Call remove in a loop over values you haven't confirmed are present
- Write {} hoping for an empty set
What does this program print?
ids = {1, 2, 3}
ids.discard(4)
ids.remove(2)
ids.discard(2)
print(ids)- {1, 2, 3}
- KeyError raised by discard(4)
- KeyError raised by discard(2)
- {1, 3}
Seat releases arrive the way the cancellations did: a list of values, some of which were never taken. Choosing the method is choosing what an absent value means. If a release for a seat nobody held is ordinary, discard lets the loop finish. If it means 2 systems disagree about the seating chart, remove stops at the first bad value and names it in the KeyError. After the loop, not in confirms each release took effect.
held = {4, 9, 12}
for seat in [9, 30]:
held.discard(seat)
print(len(held), 9 not in held)This prints 2 True. Seat 30 was never held and the loop passed over it; seat 9 left, so 9 not in held is True.
About this lesson
This section is part of the Sets: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.