The set.union() method in Python returns a new set containing all unique elements from two or more sets. It combines the given sets and automatically removes duplicate values. The original sets remain unchanged.

Example: In this example, two sets a and b are combined using union().
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
Output
{1, 2, 3, 4, 5}
Explanation: a.union(b) merges both sets. Duplicate element 3 appears only once.
Syntax
set1.union(set2, set3, ...)
- Parameters: One or more sets to be merged. If no argument is given, it returns a copy of the original set.
- Returns: Returns a new set containing all unique elements.
Examples
Example 1: In this example, union on three sets is performed using multiple union() calls and by passing multiple sets directly.
a = {2, 4, 5, 6}
b = {4, 6, 7, 8}
c = {7, 8, 9, 10}
print(a.union(b).union(c))
print(a.union(b, c))
Output
{2, 4, 5, 6, 7, 8, 9, 10}
{2, 4, 5, 6, 7, 8, 9, 10}
Explanation: a.union(b).union(c) merges sets step by step and a.union(b, c) merges all sets at once.
Example 2: Here, | operator is used as a shortcut for union operation on sets.
a = {2, 4, 5, 6}
b = {4, 6, 7, 8}
c = {7, 8, 9, 10}
print(a | b)
print(a | b | c)
Output
{2, 4, 5, 6, 7, 8}
{2, 4, 5, 6, 7, 8, 9, 10}
Explanation:
- a | b performs union of two sets.
- a | b | c merges all three sets.
- The | operator works the same as union().
Example 3: In this example, union() is applied on sets of strings.
a = {'ab', 'ba', 'cd', 'dz'}
b = {'cd', 'ab', 'dd', 'za'}
print(a.union(b))
Output
{'cd', 'za', 'ba', 'ab', 'dd', 'dz'}
Explanation:
- a.union(b) combines both sets.
- Common elements 'ab' and 'cd' appear only once.
- The result contains all unique strings.