set.difference_update()
The in-place difference — remove every element that appears in the given iterable(s). The bulk cousin of discard().
Demo
difference_update mutates the set in place. Real Python returns None; the demo shows the RESULTING state so the effect is visible. Every element that appears in the iterable is removed from the set. Elements in the iterable that are NOT in the set are silently ignored — no KeyError. The iterable can be any iterable, not just another set.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| *others | iterable | no (()) | Zero or more iterables. Every element appearing in any of them is removed from the set (if present). |
Return value
None — Returns None. The set is mutated in place — every element that appears in any of the given iterables is removed. Equivalent to `s -= set(other1) | set(other2) | ...` but takes any iterables, not just sets.
Common patterns
seen.difference_update(retired_ids)
active.difference_update(banned, expired, deleted)
s -= other_set # requires a set s.difference_update(iterable) # any iterable
s.difference_update(x for x in s if is_stale(x))
Examples
Pitfalls
s = s.difference_update(other)
s.difference_update(other)
s.difference_update(s)
s.difference_update(list(s))
{"a"}.difference_update(["z"])
missing = set(target) - s if missing: log.warning(...)
s = {"h", "i", "no"} s.difference_update("hi")
s.difference_update(["hi"])
When to use
- Removing many elements from a set given an iterable
- Subtracting multiple sources in one call
- Building a "keep" state by removing everything else
- When silence on missing elements is desired (unlike remove())
- You need a new set — use `-` or `difference()` for a pure result
- One element at a time → discard() is clearer
- You need a KeyError on missing → build the check yourself first
- You need to iterate over the removed items → compute the diff explicitly
Notes
FAQ
For a set on the right, they are equivalent: `s -= t` calls `s.difference_update(t)`. But difference_update accepts ANY iterable (list, string, generator) and multiple iterables in one call. `-=` requires a set on the right.