set.union()

Merge sets without mutating either — the pure counterpart to update.

Set methodPython 2.6+Live demo
Common call
s1 | s2
Returns
a NEW set — self and others untouched
Replaces
writing `{*s1, *s2}` or a loop of `.add()` calls
Watch out
others can be ANY iterable, not just sets — string iterables explode into chars
set.union(*others)
set

Demo

Live evaluation
Try:
Inputs
asetfirst set (comma-separated)
bsetsecond set (comma-separated)
Output
{'1', '2', '3'}.union({'4', '5', '6'})
TypeError: 'object' object is not iterable

union returns a NEW set — self is untouched. The demo input arrives as CSV; duplicates within one input collapse silently on the way in (that is what sets do). Order shown is not meaningful — Python sets are unordered; two runs may show items in different sequence.

Parameters

NameTypeRequiredDescription
*othersiterableno (())Zero or more iterables. Elements from every one are added to the result. Each iterable can be any type — set, list, tuple, generator, string, dict (keys).

Return value

setA NEW set containing every element from self and from every iterable in others. Duplicates collapse silently. Neither self nor others are modified.

Common patterns

Merge two sets
The operator form is the idiomatic one — reads like "a or b".
combined = a | b
Union many
union takes variadic args, and any iterable is accepted.
all_tags = set().union(*(post.tags for post in posts))
Deduplicate an iterable via union
Empty set union with the iterable equals the set of its elements.
unique = set().union(items)

Examples

1. Disjoint sets
{1, 2} | {3, 4}
Returns
{1, 2, 3, 4}
2. Overlapping
{1, 2, 3} | {2, 3, 4}
Returns
{1, 2, 3, 4}
3. Iterable other
{1, 2}.union([2, 3, 4])
Returns
{1, 2, 3, 4}
4. Multiple others
{1}.union({2, 3}, [3, 4], (4, 5))
Returns
{1, 2, 3, 4, 5}
5. Empty is identity
{1, 2}.union()
Returns
{1, 2} # equal, not identical

Pitfalls

1. The `|` operator requires both sides to be sets
union() accepts any iterable. The `|` operator does NOT — it needs a set on both sides. Reaching for the operator with a list raises TypeError.
Type error
{1, 2} | [3, 4]
TypeError: unsupported operand type(s) for |: 'set' and 'list'
Method form
{1, 2}.union([3, 4])
{1, 2, 3, 4}
2. union() is NOT update() — it returns a new set
union leaves both inputs alone and returns a fresh set. update mutates the left one and returns None. Same class of confusion as sort vs sorted.
Original untouched
a = {1, 2}
a.union({3, 4})
a
{1, 2} # nothing added
Two options
a = a | {3, 4}       # new set, replace name
# or
a.update({3, 4})       # mutate in place
{1, 2, 3, 4}
3. String iterables explode into characters
Passing a string as an "other" adds every character as its own element, exactly like list.extend's classic footgun.
Char explosion
{"Ann"}.union("Bob")
{"Ann", "B", "o", "b"}
Wrap it
{"Ann"}.union({"Bob"})
# or
{"Ann"}.union(["Bob"])
{"Ann", "Bob"}
4. Elements must be hashable
A union that ends up trying to store an unhashable item (list, dict, another set) raises TypeError.
Unhashable
{1, 2}.union([[3, 4]])
TypeError: unhashable type: 'list'
Use tuples
{1, 2}.union([(3, 4)])
{1, 2, (3, 4)}

When to use

Use it
  • Combining sets without mutating either
  • Deduplicating an iterable in one call
  • Composing multiple sources into a single set
  • Chaining with other pure set operations (|, &, -)
Reach for something else
  • You want to mutate in place → set.update or |=
  • Preserving insertion order → union does not; use dict.fromkeys(iter).keys()
  • Elements are unhashable → use a list or wrap in tuples
  • Small hot loops where allocation dominates → mutate with add or update

Notes

Complexity
O(|a| + sum(|other_i|))
Return
A new set — same type as self (`set` or `frozenset`)
CPython impl
Objects/setobject.c :: set_union
Memory
Allocates a new set sized for all input elements
Thread-safe
Safe against reads; not safe under concurrent writes to the input sets

FAQ

They compute the same thing, but union() accepts ANY iterable (list, tuple, generator, string). The `|` operator requires both sides to be sets. Method: flexible. Operator: strict.

History

2.3
set type added; union available as `|` operator.
2.6
union() method accepts multiple iterable arguments (variadic).