union(*others) builds a new set that holds every item found in the set or in any of the iterables you pass. Duplicates appear only once, and the original set is not changed.
The arguments can be any iterable, so a list, a tuple, or even a string works. With no arguments, union() simply returns a copy of the set.
set.union() is an instance method of the built-in set type: call it on a set with dot notation, such as club.union(...). No import is needed.
Syntax
Pass zero or more iterables, and keep the returned set in a variable.
python
result = s.union(iterable)
result = s.union(iterable1, iterable2)
result = s | other_set
Call
What it does
{1, 2}.union({2, 3})
Returns {1, 2, 3}, a new set. Neither original set changes.
{1, 2}.union([3, 4], (5,))
Returns {1, 2, 3, 4, 5}: any iterables work, and several can be passed.
{1, 2} | [3]
Raises TypeError: the | operator needs a set on both sides.
a | b is a shortcut for a.union(b), but only between two sets. To add items into the existing set instead of making a new one, use update().
Method signatures
python
set.union(*others)
# returns: a new set with the items of the set and of every iterable
# raises: TypeError if an argument is not iterable or an item is unhashable
Parameters
Parameter
Description
*others
Zero or more iterables: set, list, tuple, string, range, dict (its keys), and so on. Every item must be hashable.
Return Value
Return Value
Description
set
A new set with all the items. With no arguments it is a copy of the original, so changing it does not affect the original.
Python Examples
Example 1 — Combine Two Club Memberships
Find everyone who belongs to the chess club or the music club, and check that the originals keep their size.