Union() function in Python (original) (raw)
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 Union
The 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:
- Zero or more sets can be passed as arguments.
- If no parameter is provided, a copy of set1 is returned.
**Returns:
- A **new set containing the union of all given sets.
- Ensures **no duplicate elements in the final set.
**Union() examples
Let us see a few examples of the set union() function in Python.
**Using Union() on multiples sets
We 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))
`
Output
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:
- **A.union(B).union(C) → First, **A ∪ B results in {2, 4, 5, 6, 7, 8}. Then, **∪ C adds {9, 10}, forming {2, 4, 5, 6, 7, 8, 9, 10}.
- **A.union(B, C) → All sets are merged at once, producing the same final result.
Using | Operator
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)
`
Output
A U B: {2, 4, 5, 6, 7, 8} A U B U C: {2, 4, 5, 6, 7, 8, 9, 10}
**Explanation:
- **A | B → Combines {2, 4, 5, 6} and {4, 6, 7, 8}, removing duplicates.
- **A | B | C → Merges all three sets efficiently.
**Using Union() with Strings
union()
method works on sets of strings as well.
Python `
A = {'ab', 'ba', 'cd', 'dz'} B = {'cd', 'ab', 'dd', 'za'}
print("A U B:", A.union(B))
`
Output
A U B: {'dd', 'dz', 'ab', 'ba', 'cd', 'za'}
**Explanation:
- The elements ‘ab’ and ‘cd’ appear in both sets, so they are included only once in the final set.
- The result contains all unique elements from both sets.