Python Set – union() Method

It is a method in python that returns the union of sets. It Returns the all the element of the main set along the elements of the set(s) given in the argument. It modifies the given set and can take multiple parameters in the argument.

Syntax:
set1.union(set2,set3,…)
or
set1|(set2,set3,..)

Also Read: Python Set – issuperset() Method

Example 1:

# Python code to understand union() method in set
# www.codewindow.in

s1 = {2, 5, 8, 7, 9}
s = {10, 5}

#union of s and s1
print(s.union(s1))

#union of s1 and s
print(s1|(s))

Output:

{2, 5, 7, 8, 9, 10}
{2, 5, 7, 8, 9, 10}

Explanation:
Here, it returned all the element of the main set along with the elements of the specified set.

Example 2:

# Python code to understand union() method in set
# www.codewindow.in

s1 = {"code", "window"}
s = {"code", "website"}
s2 = {"tech", "website"}

#union of s and s1?
print(s1.union(s,s2))

Output:

{'window', 'tech', 'website', 'code'}

Explanation:
Here, it returned all the element of the main set along with the elements of the specified set (s) and set (s2).


Follow Us

You Missed

Also Checkout