set.union()
Returns a new set with every element that is in this set or in any of the others, each one only once. Same as the | operator.
set.union(*others)a.union(b) gives a new set containing everything from a and everything from b. Elements that appear in both are kept once. Neither a nor b changes.
The operator a | b does the same for two sets. The method has one advantage: its arguments can be any iterable, such as lists or tuples, and you can pass several at once.
The result is a set, so it has no order. With strings, the printed order can change between runs, so sort the result when you show it.
Parameters
| Parameter | What it is |
|---|---|
*othersoptional | Any number of sets or other iterables (lists, tuples, strings…). With none, you get a copy of the set. |
Return value
A new set. The original sets are not changed.
Examples
1Combine two sets
a = {1, 2, 3}
b = {3, 4}
print(a.union(b))
print(a | b)
print(a){1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3}2Everyone who attended any session
monday = {"Ana", "Ben"}
tuesday = {"Ben", "Chloe"}
friday = {"Dan", "Ana"}
all_people = monday.union(tuesday, friday)
print(len(all_people))
print(sorted(all_people))4 ['Ana', 'Ben', 'Chloe', 'Dan']
sorted() gives a stable order; printing the set of names directly could show them in a different order on each run.
3Lists work as arguments too
tags = {"python", "web"}
new_tags = ["web", "data", "python"]
print(sorted(tags.union(new_tags)))
try:
tags | new_tags
except TypeError:
print("TypeError: | needs two sets")['data', 'python', 'web'] TypeError: | needs two sets
Common mistakes
Expecting union() to change the set
union() returns a new set. To add the elements to the existing set, use set.update() or a |= b.
a = {1, 2}
a.union({3})
print(a)
a.update({3})
print(a){1, 2}
{1, 2, 3}Using + to join sets
Sets do not support +; it raises TypeError. Use | or union().
Questions people ask
What is the difference between union() and update()?
union() returns a new set. set.update() adds the elements into the existing set and returns None.
How do I merge two lists without duplicates?
sorted(set(a).union(b)), or list(dict.fromkeys(a + b)) to keep the original order.