Home » Python

Python Set union() Method with Example

Python Set union() Method: Here, we are going to learn how to find the union of all sets in Python?
Submitted by IncludeHelp, on December 01, 2019

Set union() Method

union() method 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 arguments, method returns the set containing all elements of all sets (common elements repeat only once).

Syntax:

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

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:

# Python Set union() Method with Example

# 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:

# Python Set union() Method with Example

# 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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.