12.7 Set Operators
Union (|), intersection (&), difference (-), and symmetric difference (^) as real mathematical set operations applied directly to Python sets, plus O(1) average membership testing with in and not in.
Sets support real mathematical set operations directly as operators — the same conceptual operations from set theory, applied to Python collections.
| (Union)
Everything in either set (or both) — combines all unique elements.
>>> a, b = {1, 2, 3}, {2, 3, 4}
>>> a | b
{1, 2, 3, 4}
& (Intersection)
Only elements in both sets.
>>> a & b
{2, 3}
- (Difference)
Elements in the first set but not the second — order matters here, unlike union/intersection.
>>> a - b
{1}
^ (Symmetric Difference)
Elements in exactly one of the two sets (i.e. everything except the overlap).
>>> a ^ b
{1, 4}
Membership (in, not in)
The operation sets are famous for — O(1) average, versus O(n) for the same check on a list (see 10.6 List Operators).
>>> 2 in a, 5 not in a
(True, True)
Quick Interview Answer
“Sets support four operators straight out of set theory:
|for union (everything in either),&for intersection (only what’s in both),-for difference (in the first but not the second — order matters here, unlike the other three), and^for symmetric difference (in exactly one, not both). Each has a method equivalent too (see 12.8 Set Methods), useful when chaining or passing as a callback. Andin/not inmembership testing is the operation sets exist for — O(1) average via a direct hash lookup, versus O(n) for the same check on a list.”
Common Mistakes
- Assuming
-is symmetric like|and&—a - bandb - aare generally different sets; only^is order-independent for “what differs.” - Forgetting that
|,&, and-all build a new set rather than mutating either operand. - Reaching for a list and a manual loop to find common or missing elements between two collections, instead of converting to sets and using
&or-directly (see 12.14 Common Algorithms).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form