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

← All Python set methods · List methods · list vs tuple vs set