union
set.union
Returns a NEW set containing every element that appears in s or any of the arguments. The method accepts any iterable(s); the | operator requires all operands to be sets or frozensets.
s.union(*others) | s | other Parameters
| Parameter | Purpose |
|---|---|
| *others | Zero or more iterables (method form) or sets (operator form) |
| returns | A new set — s is not modified |
Examples
>>> {1, 2} | {2, 3}
{1, 2, 3} | operator between two sets.
>>> {1, 2}.union([2, 3], (3, 4))
{1, 2, 3, 4} Method accepts any iterables.
>>> {1, 2} | [2, 3]
TypeError: unsupported operand type(s) for |: 'set' and 'list' Operator rejects non-set operands.
>>> a = {1, 2}
>>> b = a.union({3})
>>> a
{1, 2} Original set is unchanged.
Gotcha
The | operator only works between sets/frozensets — use .union() with a plain list or generator. Both forms return a NEW set (use update / |= to mutate in place).
Related methods
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
set.intersection
Returns a NEW set containing only elements found in s AND in every argument. Method form accepts any iterables; & requires sets.
set.difference
Returns a NEW set with elements from s that are NOT in any of the arguments. Method form takes iterables; - requires sets.
← All Python set methods · List methods · list vs tuple vs set