Example 1 — Book a Seat From the Free List
Take one seat out of the free set, then try to book it a second time.
free = {"A1", "A2", "B1", "B2"}
booked = "B1"
free.remove(booked)
print(sorted(free))
print(booked in free)
try:
free.remove(booked)
except KeyError:
print(booked, "was not available") How It Works
- One seat leaves.
remove("B1")deletes that seat, so three seats are left in the set. - Membership proves it.
booked in freeis nowFalse, because the seat is gone. - A second removal fails. The seat is no longer in the set, so
remove()raisesKeyError, which theexceptblock catches.

