Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.union() method

Reference for Python set.union(): combine sets or any iterables into a new set, the | operator, multiple arguments, frozensets and the difference from update().

The union() method returns a new set containing every element that appears in the set or in any of the other collections. Duplicates collapse, because a set holds each value once.

The operator form is a | b. The original sets do not change; if you want to add the elements to an existing set, use update() or |=.

Python
{1, 2}.union({2, 3}, [4])   # {1, 2, 3, 4}

Try it

Python Combining sets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Method, operator and type rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.union(*others)
set | other | ...
Name Description
*others Zero or more iterables. All their items must be hashable.

Return value: a new set with all elements.

Raises: TypeError if an argument is not iterable (method), is not a set (operator), or contains unhashable items.

Usage notes

  • Returns a new set. Nothing is modified. Use update() or |= to grow a set in place.
  • The method accepts any iterable and several arguments; the operator requires sets or frozensets on both sides.
  • Union of a list of sets: set().union(*groups). The set() start matters, because set.union(*groups) fails for an empty list.
  • Result type follows the left operand, so frozenset | set is a frozenset and set | frozenset is a set.
  • Order is not preserved. Print with sorted() when you need stable output.
  • With no arguments, s.union() is a shallow copy.
  • Cost is proportional to the total size of the inputs.