Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
union
merge
set
communitycreator

What is the union() method in Python?

Mahnoor Zaheer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The union() method in Python merges the items of two or more sets. If two or more sets contain the same element, it will appear only once in the returning set.

Syntax

The syntax of this method is as follows.


set.union(set1, set2..., setn)

Parameters

The union() method takes one required parameter, which is a set. Apart from this parameter, it can take multiple optional arguments, which are also set.

Return value

The return value is a set that contains joined elements of the sets on which union() is applied.

Code

Example 1

Two sets are merged through the union() method in the code below.

#set declaration
set1 = {"1", "2", "3"}
set2 = {"c", "b", "a"}

#union application on sets
setUnion = set1.union(set2)

print(setUnion)
The union() method applied on two sets

Example 2

The union() method is applied at more than one set and returns a set that contains all the elements of these sets.

Also, set1 and set3 contain some values that are the same, and hence they appear only once in the resulting set.

#set declaration
set1 = {"1", "2", "3"}
set2 = {"6", "7", "8"}
set3 = {"3", "4", "5"}

#union application on sets
setUnion = set1.union(set2, set3)

print(setUnion)
The union() method applied on more than two sets

RELATED TAGS

python
union
merge
set
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring