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

Example: Perform union of two sets

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

print(A.union(B))

Output:

{'blue', 'green', 'yellow', 'orange', 'red'}

Venn Diagram:

Set union

Equivalent Operator |

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

Example:

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

# by method
print(A.union(B))

# by operator
print(A | B)

Output:

{'blue', 'green', 'yellow', 'orange', 'red'}

Union of Multiple Sets

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

Example:

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

# by method
print(A.union(B,C))

# by operator
print(A | B | C)

Output:

{'blue', 'green', 'yellow', 'orange', 'black', 'red'}