How to Remove an Item from a Set in Python

To remove an item from a set in Python, call s.remove(x) when the item must be there (it raises KeyError if not) or s.discard(x) when it might be missing. A meetup organizer in Austin needed both for her door list.

pending.remove("Emily Carter")   # KeyError if missing
pending.discard("Grace Kim")     # silent if missing

In this tutorial, I’ll build her check-in script step by step, and you’ll see every way to remove item from set in Python: one item, several at once, items matching a rule, and the whole set.

Here’s what we’re building. Twelve RSVPs go in; check-ins, cancellations, no-shows and placeholder badges come out:

Command Prompt output of a Python check-in script removing names from a set of 12 RSVPs and leaving 4 expected guests
Of 12 RSVPs, 4 guests are still expected, and two real cancellations add up to $50.00 in refunds.

Every output here comes from real runs on Python 3.12.5, shown in Command Prompt.

Before You Start: the RSVP set we’ll remove items from

You only need Python 3. A set holds unique, unordered items, which makes it a natural guest list; creating an empty set in Python covers the basics.

The event is Austin Python Night on December 3, 2026, with $25.00 tickets. Here’s what happens to each RSVP:

NameWhat happensMethod
Emily Carter, James MillerCheck inremove()
Ava Thompson, Liam Walker, Grace KimCancel (Grace never RSVP’d)discard()
Harper Collins, Ethan PriceNo-showsdifference_update()
GUEST-01, GUEST-02Placeholder badgescomprehension
Olivia Brooks, Noah Davis, Sophia Reed, Mason HayesStill expectedpop(), clear()

Save the RSVPs as rsvps.py. Every script below imports this one sample and copies it with set(RSVPS), so the original never changes:

RSVPS = {
    "Emily Carter", "James Miller", "Olivia Brooks", "Noah Davis",
    "Ava Thompson", "Liam Walker", "Sophia Reed", "Mason Hayes",
    "Harper Collins", "Ethan Price", "GUEST-01", "GUEST-02",
}

Step 1: Remove one item from the set with remove()

Emily and James walk in. remove() deletes an item in place and returns None. Calling it again for Emily shows what happens when the item is gone:

from rsvps import RSVPS

pending = set(RSVPS)
result = pending.remove("Emily Carter")
pending.remove("James Miller")
print("returned:", result, "| left:", len(pending))

pending.remove("Emily Carter")      # already gone

Output:

returned: None | left: 10
Traceback (most recent call last):
  File "C:\pyguides\remove_one.py", line 8, in <module>
    pending.remove("Emily Carter")      # already gone
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'Emily Carter'
Command Prompt output of Python set remove() returning None, leaving 10 items, then raising KeyError for a name already removed
Two removals leave 10 names; removing Emily again raises KeyError: 'Emily Carter'.

At the door, that error is useful: it says a name isn’t on the list. Adding names works the other way round, as in adding items to a set in Python.

Checkpoint: returned: None | left: 10, then the traceback.

Step 2: Remove an item that might be missing with discard()

Some cancellations come from people who never RSVP’d. discard() removes an item if it’s there and does nothing if it isn’t:

from rsvps import RSVPS

pending = set(RSVPS)
refunds = 0.0
for name in ["Ava Thompson", "Liam Walker", "Grace Kim"]:
    if name in pending:
        refunds += 25.00
    pending.discard(name)           # Grace Kim never RSVP'd
print("left:", len(pending), f"| refunds: ${refunds:.2f}")

Output:

left: 10 | refunds: $50.00
Command Prompt output of Python set discard() removing two cancelled guests, ignoring a missing name and totaling $50.00 in refunds
Two names leave, Grace Kim is skipped quietly, 10 remain and refunds total $50.00.

I test membership first only because refunds go to real RSVPs; the in operator in Python explains that check.

Step 3: Remove multiple items from a set at once

Two people never showed. Set difference removes a group without a loop: - builds a new set, while difference_update() and -= change the one you have:

from rsvps import RSVPS

pending = set(RSVPS)
no_shows = ["Harper Collins", "Ethan Price"]

left = pending - set(no_shows)      # new set, pending unchanged
print(len(pending), len(left))

pending.difference_update(no_shows)  # in place, any iterable
print(len(pending))
pending -= {"Mason Hayes"}           # same thing as an operator
print(len(pending), "Mason Hayes" in pending)

Output:

12 10
10
9 False
Command Prompt output of Python set difference and difference_update removing multiple no-show names from the RSVP set
pending - set(no_shows) leaves the original at 12; difference_update() drops it to 10 and -= to 9.

difference_update() takes any iterable, but -= needs a set. Group operations like this are why a set beats a list for guest lists.

Checkpoint: 12 10, then 10, then 9 False.

Step 4: Remove items that match a condition

The GUEST- badges must go. The obvious loop fails, because a set can’t change size while you loop over it:

from rsvps import RSVPS

pending = set(RSVPS)
for name in pending:
    if name.startswith("GUEST"):
        pending.remove(name)        # changes the set mid-loop

Output:

Traceback (most recent call last):
  File "C:\pyguides\loop_remove.py", line 4, in <module>
    for name in pending:
                ^^^^^^^
RuntimeError: Set changed size during iteration
Command Prompt output of Python RuntimeError Set changed size during iteration when removing set items inside a for loop
Removing inside the loop stops with RuntimeError: Set changed size during iteration.

Build a new set with a comprehension instead. The syntax matches list comprehension in Python, with braces:

from rsvps import RSVPS

pending = set(RSVPS)
pending = {n for n in pending if not n.startswith("GUEST")}
print(len(pending), "GUEST-01" in pending)

Output:

10 False
Command Prompt output of a Python set comprehension removing GUEST placeholder badges and leaving 10 names
The comprehension leaves 10 names, and GUEST-01 is gone.

If you’d rather keep the loop, iterate over a copy: for name in list(pending): lets you call remove() safely.

Step 5: Empty the set with pop() and clear()

Four badges are left. pop() removes and returns an arbitrary item, so a while loop drains the set; clear() empties it at once:

pending = {"Olivia Brooks", "Noah Davis", "Sophia Reed", "Mason Hayes"}
handed = []
while pending:
    handed.append(pending.pop())    # takes any item, not a random one
print("handed out:", len(handed), "| left:", len(pending))
print(", ".join(sorted(handed)))

walk_ins = {"Grace Kim", "Lucas Ward"}
walk_ins.clear()
print(walk_ins, len(walk_ins))
pending.pop()                       # pop() on an empty set

Output:

handed out: 4 | left: 0
Mason Hayes, Noah Davis, Olivia Brooks, Sophia Reed
set() 0
Traceback (most recent call last):
  File "C:\pyguides\pop_clear.py", line 11, in <module>
    pending.pop()                       # pop() on an empty set
    ^^^^^^^^^^^^^
KeyError: 'pop from an empty set'
Command Prompt output of Python set pop() draining four names, clear() leaving set() and pop() on an empty set raising KeyError
All 4 names come out, clear() leaves set(), and pop() on an empty set raises KeyError.

Important: pop() isn’t random, so don’t draw a raffle winner with it. To test for an empty set, see checking if a Python set is empty.

Test the check-in script

Here’s the finished checkin.py. The if __name__ guard lets another file import run_door() safely; running a Python script covers the command:

from rsvps import RSVPS

TICKET = 25.00


def run_door(pending, arrived, cancelled, no_shows):
    for name in arrived:
        try:
            pending.remove(name)        # must be on the list
        except KeyError:
            print(f"  ! {name} is not on the RSVP list")
    refunds = 0.0
    for name in cancelled:
        if name in pending:
            refunds += TICKET
        pending.discard(name)           # no error if missing
    pending -= set(no_shows)            # several at once
    pending = {n for n in pending if not n.startswith("GUEST")}
    return pending, refunds


if __name__ == "__main__":
    pending, refunds = run_door(
        set(RSVPS),
        arrived=["Emily Carter", "James Miller"],
        cancelled=["Ava Thompson", "Liam Walker", "Grace Kim"],
        no_shows=["Harper Collins", "Ethan Price"],
    )
    print(f"RSVPs: {len(RSVPS)}  still expected: {len(pending)}")
    print("Waiting on:", ", ".join(sorted(pending)))
    print(f"Refunds due: ${refunds:.2f}")

Output:

RSVPs: 12  still expected: 4
Waiting on: Mason Hayes, Noah Davis, Olivia Brooks, Sophia Reed
Refunds due: $50.00

Now a volunteer types Emely instead of Emily, and remove() flags it:

from checkin import RSVPS, run_door

pending, refunds = run_door(
    set(RSVPS),
    arrived=["Emely Carter", "James Miller"],   # typo at the door
    cancelled=[], no_shows=[],
)
print("still expected:", len(pending), "| refunds:", f"${refunds:.2f}")
print("Emily Carter" in pending)

Output:

  ! Emely Carter is not on the RSVP list
still expected: 9 | refunds: $0.00
True
Command Prompt output of a test importing the Python check-in script, flagging a misspelled name that remove() could not find
The typo is flagged, refunds stay at $0.00, and True confirms Emily Carter is still on the list.

With discard() there, Emily would silently look like a no-show.

Can you remove an item from a set by index?

No. Sets have no positions, so del pending[0] raises TypeError. Convert the set to a list first, then use the list tools in deleting an element from a Python list.

Troubleshooting errors when you remove set items

The KeyError from remove() and pop() works like KeyError in a Python dictionary: switch to discard(), or loop with while s:.

An AttributeError on discard means a frozenset, which is immutable in Python. Copy it with set(fs).

Where to Take It Next with your check-in script

Load the RSVP names from a text export instead of typing them; reading a file into a list in Python gets you there.

If you keep building with sets, these tutorials fit well alongside this one:

Frequently asked questions

How do I remove an item from a set in Python?

Use s.remove(x), or s.discard(x) if the item may be missing.

What’s the difference between remove() and discard()?

remove() raises KeyError for a missing item; discard() does nothing.

How do I remove multiple items from a set?

Use s.difference_update(items) or s -= set(items).

Does set.pop() remove a random item?

No. It removes an arbitrary item, which isn’t the same as random.

Why do I get ‘Set changed size during iteration’?

You removed items while looping over the set. Loop over list(s) instead.

Where are the set methods documented?

See set types in the Python docs.