Easy Tutorial
❮ Python Merging Two Dictionaries Python Func Tuple ❯

Python Set union() Method

Python Set


Description

The union() method returns the union of two sets, which includes all elements from both sets, with duplicate elements appearing only once.

Syntax

The syntax for the union() method is:

set.union(set1, set2...)

Parameters

Return Value

Returns a new set.

Example

Combining two sets, with duplicate elements appearing only once:

Example 1

x = {"apple", "banana", "cherry"}
y = {"google", "tutorialpro", "apple"}

z = x.union(y)

print(z)

Output:

{'cherry', 'tutorialpro', 'google', 'banana', 'apple'}

Combining multiple sets:

Example 2

x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}

result = x.union(y, z)

print(result)

Output:

{'c', 'd', 'f', 'e', 'b', 'a'}

Python Set

❮ Python Merging Two Dictionaries Python Func Tuple ❯