Table of Contents
In this tutorial, we will learn about the Python Set union() method with the help of example.
The Python set union() method returns a new set with distinct elements from all the sets.
Example
A = {2, 3, 5}
B = {1, 3, 5}
# compute union between A and B
print('A U B = ', A.union(B))
# Output: A U B = {1, 2, 3, 5}
1. Syntax of Set union()
The syntax of union() is:
A.union(*other_sets)
Note: * is not part of the syntax. It is used to indicate that the method can take 0 or more arguments.
2. Return Value from union()
- The
union()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.
3. Example 1: Python Set union()
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}
print('A U B =', A.union(B))
print('B U C =', B.union(C))
print('A U B U C =', A.union(B, C))
print('A.union() =', A.union())
Output
A U B = {2, 'a', 'd', 'c'}
B U C = {1, 2, 3, 'd', 'c'}
A U B U C = {1, 2, 3, 'a', 'd', 'c'}
A.union() = {'a', 'd', 'c'}
4. Working of Set Union
The union of two or more sets is the set of all distinct elements present in all the sets. For example:
A = {1, 2}
B = {2, 3, 4}
C = {5}
Then,
A∪B = B∪A = {1, 2, 3, 4}
A∪C = C∪A = {1, 2, 5}
B∪C = C∪B = {2, 3, 4, 5}
A∪B∪C = {1, 2, 3, 4, 5}

5. Example 2: Set Union Using the | Operator
You can also find the union of sets using the | operator.
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}
print('A U B =', A| B)
print('B U C =', B | C)
print('A U B U C =', A | B | C)
Output
A U B = {2, 'a', 'c', 'd'}
B U C = {1, 2, 3, 'c', 'd'}
A U B U C = {1, 2, 3, 'a', 'c', 'd'}
Related posts:
Python float()
Python Program to Concatenate Two Lists
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Check Prime Number
Python zip()
Python List remove()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python len()
Python Errors and Built-in Exceptions
Python Program to Multiply Two Matrices
Python Dictionary popitem()
Python Program to Find HCF or GCD
Python Program to Merge Mails
Python Program to Compute the Power of a Number
Python String find()
Python Program to Count the Number of Digits Present In a Number
Python Program to Extract Extension From the File Name
Python Dictionary fromkeys()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Differentiate Between del, remove, and pop on a List
Python getattr()
Python Program to Solve Quadratic Equation
Python Dictionary get()
Python Program to Iterate Over Dictionaries Using for Loop
Python String encode()
Python frozenset()
Python String lower()
Python String partition()
Python Program to Count the Occurrence of an Item in a List
Python *args and **kwargs
Python Dictionary copy()