Python Set union()
Python Set x.union(y)
method finds the union of set x
and set y
and returns the resulting set. We can pass more than one set to the union() method as arguments.
In this tutorial, we will learn the syntax of set.union() method and go through examples covering different scenarios for the arguments that we pass to union() method.
Syntax
The syntax of set.issubset() method is
set.union(set1, set2...)
where
Parameter | Description |
---|---|
set, set1, set2… | Sets whose union has to be found out. |
The method returns a set with elements from all the sets.
Examples
1. Union of two sets
In the following program, we will take two sets: x
, y
; and find their union.
Python Program
x = {'apple', 'banana', 'cherry'}
y = {'apple', 'banana', 'mango', 'guava'}
result = x.union(y)
print(result)
Program Output
{'apple', 'banana', 'guava', 'cherry', 'mango'}
2. Union of three sets
In the following program, we take three sets: x
, y
, z
; and find their union.
Python Program
x = {'apple', 'banana', 'cherry'}
y = {'apple', 'mango', 'guava'}
z = {'cherry', 'kiwi'}
result = x.union(y, z)
print(result)
Program Output
{'kiwi', 'mango', 'guava', 'cherry', 'banana', 'apple'}
Conclusion
In this Python Tutorial, we learned about Python set method union(). We have gone through the syntax of union() method, and its usage with example programs.