CKTIS / Python
Set union with `|`
Use `|` to combine sets without changing either operand. With two integers, the same operator performs bitwise OR instead.
Version: Python 3.12
Syntax
a | b
a.union(b)In Python 3.12, set | refers to the set-union use of |. Given two sets, a | b creates a new set containing every element that appears in either input. An element shared by both appears only once. Neither operand changes, and the result has no guaranteed element order.
For union between built-in sets, both operands must be set or frozenset. If you mix the two types, the result has the type of the left operand. If your input is a list, use a.union([2, 4]): the method accepts an iterable of hashable elements. By contrast, a | [2, 4] raises TypeError when a is a built-in set.
The operand types determine what | does. With two int values, it performs bitwise OR: each result bit is 1 if the corresponding bit is 1 in at least one operand. In a set of integers, each integer remains a whole element; its bits are not combined with those of other integers.
Examples
a = {1, 2}
b = {2, 4}
combined = a | b
print(sorted(combined))
print(5 | 3)Result
[1, 2, 4] 7
`2` is in both input sets but appears only once in their union. `sorted()` returns an ordered list for display; the union itself remains a set. The second line shows integer bitwise OR: `5 | 3` gives `7`.
Related lessons
- Python · Lesson 18 · Basic · Version: 3