FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Python Set union() method with examples




The Set union() method returns a new set with the distinct elements from all the given Sets. The union is denoted by ∪ symbol. Lets say we have a Set A: {1, 2, 3} and Set B: {2, 3, 4} then to find the union of these sets we can call this method either like this A.union(B) or B.union(A) and the returned set would contain the elements {1, 2, 3, 4}.

Set union() method Syntax

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

Parameter: This method accepts sets as parameters.
Return Value: This method returns a set with the distinct elements of all the sets.

Python Set union() method example

In the following example we have three sets and we are finding union of sets X & Y, X & Z and X, Y & Z using union() method. We can also use | operator to find the union of sets.

# Set X
X = {1, 2, 3}

# Set Y
Y = {2, 3, 4}

# Set Z
Z = {5, 6, 7}

print("X ∪ Y:", X.union(Y))
print("X ∪ Z:", X.union(Z))
print("X ∪ Y ∪ Z:", X.union(Y, Z))






Leave Comment