Python Set union() Method (with Examples)

Python Set union() Method: In this tutorial, we will learn about the union() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set union() Method

The union() is an inbuilt method of the set class that is used to find the union of all sets, this method is called with this set (set1) and other sets (set1, set2, ...) can be supplied as an argument, it returns the set containing all elements of all sets (common elements repeat only once).

Syntax

The following is the syntax of union() method:

set1.union(set2, set3, ...)

Parameter(s):

The following are the parameter(s):

  • set2, set3, ... – Here, set2 is required and other sets are optional.

Return Value

The return type of this method is <class 'set'>, it returns the set of the all elements.

Example 1: Use of Set union() Method

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# finding the union of both sets
x = cars_1.union(cars_2)

# print the set
print("cars_1: ", cars_1)
print("cars_2: ", cars_2)
print("x: ", x)

Output

cars_1:  {'Porsche', 'Audi', 'Lexus'}
cars_2:  {'Porsche', 'Mazda', 'Lincoln'}
x:  {'Porsche', 'Mazda', 'Lincoln', 'Audi', 'Lexus'}

Example 2: Use of Set union() Method

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}

# finding the union of all sets

result = x.union(y,z)

# printing the sets
print("x: ", x)
print("y: ", y)
print("result: ", result)

Output

x:  {'ABC', 'PQR', 'XYZ'}
y:  {'ABC', 'PQR', 'XYZ'}
result:  {'PQR', 'MNO', 'DEF', 'ABC', 'XYZ'}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.