Python Set union() Method
Description
The union() method returns the union of two sets, that is, it contains the elements of all sets, with duplicate elements appearing only once.
Syntax
Syntax of the union() method:
set.union(set1, set2...)
Parameters
- set1 -- required, the target set to merge
- set2 -- optional, other sets to merge; multiple sets are allowed, separated by commas.
Return Value
Returns a new set.
Example
Merge two sets; duplicate elements appear only once:
Example 1
x
= {
"
apple
"
,
"
banana
"
,
"
cherry
"
}
y
= {
"
"
,
"
runoob
"
,
"
apple
"
}
z
=
x
.
union
(
y
)
(
z
)
The output is:
{'cherry', 'runoob', '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
)
(
result
)
The output is:
{'c', 'd', 'f', 'e', 'b', 'a'}
Python Sets