all Python 3Sets (set)function
set.union
set theory
Return a new set with all elements from this set and the others (union). Operator: |.
Syntax
s.union(*others)
union accepts any iterables — lists, tuples, strings, generators — while the | operator only works between sets, which is why {1, 2} | [3] raises TypeError. The method builds a new set and leaves the original untouched; to grow an existing set in place, use update instead.
Examples
print(sorted({1, 2}.union({2, 3}))) # → [1, 2, 3]
print(sorted({1}.union({2}, {3}))) # → [1, 2, 3]
print(sorted({1, 2} | {2, 3})) # → [1, 2, 3]
print(sorted({1, 2}.union([2, 3], (4,)))) # → [1, 2, 3, 4]
print(sorted(set('abc').union('bcd'))) # → ['a', 'b', 'c', 'd']
print({1, 2} | [3]) # → TypeError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy