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,...)

**Parameters:** 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))

**Output:**

## Finding union of sets using | operator

Lets take the same example that we have seen above, however here we will use the | operator instead of union() method 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|Y) print("X ∪ Z:", X|Z) print("X ∪ Y ∪ Z:", X|Y|Z)

**Output:**

X ∪ Y: {1, 2, 3, 4} X ∪ Z: {1, 2, 3, 5, 6, 7} X ∪ Y ∪ Z: {1, 2, 3, 4, 5, 6, 7}

## Leave a Reply