Last Updated : 22 Feb, 2025
Union() method in Python is an inbuilt function provided by the set data type. It is used to combine multiple sets into a single set, containing all unique elements from the given sets. It ensures that no duplicate values exist in the final set.
Python Set UnionThe symbol for denoting union of sets is 'U'.
Example:
Python
A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B)) # Combining both sets
Union() Syntax
set1.union(set2, set3, ...)
Parameters:
Returns:
Let us see a few examples of the set union() function in Python.
Using Union() on multiples setsWe can merge three or more sets at once .
Python
A = {2, 4, 5, 6}
B = {4, 6, 7, 8}
C = {7, 8, 9, 10}
# using multiple union calls
print("A U B U C:", A.union(B).union(C))
# directly passing multiple sets
print("A U B U C:", A.union(B, C))
A U B U C: {2, 4, 5, 6, 7, 8, 9, 10} A U B U C: {2, 4, 5, 6, 7, 8, 9, 10}
Explanation:
we can use the | (pipe operator) as a shortcut for performing a union operation on sets.
Python
A = {2, 4, 5, 6}
B = {4, 6, 7, 8}
C = {7, 8, 9, 10}
# Using | operator for union
print("A U B:", A | B)
print("A U B U C:", A | B | C)
A U B: {2, 4, 5, 6, 7, 8} A U B U C: {2, 4, 5, 6, 7, 8, 9, 10}
Explanation:
union()
method works on sets of strings as well.
A = {'ab', 'ba', 'cd', 'dz'}
B = {'cd', 'ab', 'dd', 'za'}
print("A U B:", A.union(B))
A U B: {'dd', 'dz', 'ab', 'ba', 'cd', 'za'}
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4