Python Set union() Method
Description
The union() method returns the union of two sets, i.e., it contains all elements from the sets, and duplicate elements appear only once.
Syntax
The syntax of the union() method is as follows:
set.union(set1, set2...)
Parameters
- set1 -- Required, the target set for merging
- set2 -- Optional, other sets to merge, can be multiple, using commas to,separate them.
Return Value
Returns a new set.
Example
Merge two sets, duplicate elements will appear only once:
Example 1
x = {"apple", "banana", "cherry"}
y = {"google", "example", "apple"}
z = x.union(y)
print(z)
The output result is:
{'cherry', 'example', 'google', 'banana', 'apple'}
Merge multiple sets:
Example 1
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
result = x.union(y, z)
print(result)
The output result is:
{'c', 'd', 'f', 'e', 'b', 'a'}
Python Sets