set · Python

Set operators | & - ^

Union, intersection, difference and symmetric difference, as new sets or in place.

s | t, s & t, s - t, s ^ t; s.union(*others) …; s |= t …

Complexity

AverageO(len(s) + len(t)) for union; O(min(len(s), len(t))) for intersection; O(len(s)) for difference
Extra spaceO(size of the result)

Each element costs an average O(1) lookup or insert. Intersection iterates over the smaller set and probes the larger one.

Tested example

a, b = {1, 2, 3}, {3, 4}
assert a | b == {1, 2, 3, 4}  # union: new set
assert a & b == {3}  # intersection
assert a - b == {1, 2}  # difference
assert a ^ b == {1, 2, 4}  # symmetric difference
a |= b  # in place, like a.update(b)
assert a == {1, 2, 3, 4}
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_set.py

Parameters

t
Another set (the method forms accept any iterable).

Behaviour

Returns
A new set (operators) or None (in-place forms).
Errors and preconditions
TypeError when an operator gets a non-set operand.
Changes
Only the in-place forms (|=, &=, -=, ^=) change s.
Memory and invalidation
The operator forms allocate a new set.