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
| Average | O(len(s) + len(t)) for union; O(min(len(s), len(t))) for intersection; O(len(s)) for difference |
|---|---|
| Extra space | O(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}
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.