Python Set union() Method

Python Set union() method returns a new set with unique elements from all the sets. The result will contain only one item’s appearance if the element is present in more than one set.

For example, if A = {2,5,7} and B = {1,2,5,8} are two sets, then the Union of these two sets will be AUB={1,2,5,7,8}, though 2 and 5 are common in both the sets, but in result set it will be taken only once.

Visual Representation

Visual Representation of Python Set Union() Method

Syntax

set1.union(set2, set3, set4...)

Parameters

set1 It is required. The iterable to unify with
set2 It is optional. The other is iterable to unify with.
You can compare as many iterables as you like.
Separate each iterable with a comma.

Return Value

This method returns a new set with elements from the set and all other sets (passed as an argument). If the argument is not passed to union(), it returns a shallow copy of the set.

Example 1: How to Use Set union() Method

set1 = {2, 4, 6, 8, 10}

# Multiple of 3 between 1 to 10
set2 = {3, 6, 9}

# All prime numbers between 1 to 10
set3 = {2, 3, 5, 7}

# priting both the sets
print("Set1 is: ", set1)
print("Set2 is : ", set2)
print("Set3 is: ", set3)

# Now we will find Union of these sets
print("Union of set1 and set2 is: ", set1.union(set2))
print("Union of set1 and set2,set3 is: ", set1.union(set2, set3))

Output

Set1 is: {2, 4, 6, 8, 10}
Set2 is : {9, 3, 6}
Set3 is: {2, 3, 5, 7}

Union of set1 and set2 is: {2, 3, 4, 6, 8, 9, 10}
Union of set1 and set2,set3 is: {2, 3, 4, 5, 6, 7, 8, 9, 10}

Example 2: Set Union Using the | Operator

set1 = {2, 4, 6, 8, 10}

# Multiple of 3 between 1 to 10
set2 = {3, 6, 9}

# All prime numbers between 1 to 10
set3 = {2, 3, 5, 7}

# priting both the sets
print("Set1 is: ", set1)
print("Set2 is : ", set2)
print("Set3 is: ", set3)

# Now we will find Union of these sets
print("Union of set1 and set2 is: ", set1 | set2)
print("Union of set1 and set2,set3 is: ", set1 | set2 | set3)

Output

Set1 is: {2, 4, 6, 8, 10}
Set2 is : {9, 3, 6}
Set3 is: {2, 3, 5, 7}

Union of set1 and set2 is: {2, 3, 4, 6, 8, 9, 10}
Union of set1 and set2,set3 is: {2, 3, 4, 5, 6, 7, 8, 9, 10}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.