Python Set union() Method

Returns a set with items from all the specified sets

Usage

The union() method returns a new set containing all items from all the specified sets, with no duplicates.

You can specify as many sets as you want, just separate each set with a comma.

If you want to modify the original set instead of returning a new one, use update() method.

Syntax

set.union(set1,set2…)

Python set union() method parameters
ParameterConditionDescription
set1, set2…OptionalA comma-separated list of one or more sets to merge with.

Basic Example

# Perform union of two sets
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

print(A.union(B))
# Prints {'blue', 'green', 'yellow', 'orange', 'red'}
Set union

Equivalent Operator |

Set union can be performed with the | operator as well.

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

# by method
print(A.union(B))
# Prints {'blue', 'green', 'yellow', 'orange', 'red'}

# by operator
print(A | B)
# Prints {'blue', 'green', 'yellow', 'orange', 'red'}

Union of Multiple Sets

Multiple sets can be specified with either the operator or the method.

A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

# by method
print(A.union(B,C))
# Prints {'blue', 'green', 'yellow', 'orange', 'black', 'red'}

# by operator
print(A | B | C)
# Prints {'blue', 'green', 'yellow', 'orange', 'black', 'red'}