Python Set union() Method Tutorial

In this section, we will learn what the Set union() method is and how to use it in Python.

What is Set union() Method in Python?

The Python Set union() method is used to combine all the elements of the original Set (the one that invoked this method) and a Set object that we specify as the argument of the method.

Note: If the specified reference Set object had an element that the original Set already has, it won’t be used in the union Set object.

Python Set union() Method Syntax:

set.union(referenceSet)

Set union() Method Parameter:

The method takes one argument and that is a reference to the Set object we want to union with the original Set.

Set union() method Return Value

The return value of this method is a new Set object, which is a union of both original and reference Set objects.

Example: using python set union() method

set1 = {1,2,3,4,5,6,7,8,9,10}

set2 = {1,2,3,4,5,500,600,700}

result = set1.union(set2)

print(set1)

print(set2)

print(result)

Output:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

{1, 2, 3, 4, 5, 500, 600, 700}

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 500, 600, 700}
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies