Crus4

logo

Sets Union in Python


In Python, if we have two Sets, set A and set B, the Union of Set combines all the unique elements from both the Sets into a new set. We use the union() method or the | operator to perform union of two Sets. Here is an example:

Example

a = {1, 2, 3}
b = {3, 4, 5}
# Using the union() method
c = a.union(b)
print(c)  # Outputs: {1, 2, 3, 4, 5}

# Using the | operator
d = set1 | set2
print(d)  # Outputs: {1, 2, 3, 4, 5}

Example Explained

In an above example, a and b are two sets. The union() method performs the union operation on these two Sets, and returns the new Set that contains all the unique items of Set a and Set b. We can also use the | operator to achieve the same results.

Union Operation on Three Sets

To perform the union operation on three or more sets in Python, we have to use the union() method or the | operator. Here is an example:

Example

seta = {1, 2, 3}
setb = {3, 4, 5}
setc = {3, 6, 7}

# Using the union() method
setd = seta.union(setb, setc)
print(setd)  # Output: {1, 2, 3, 4, 5, 6, 7}

Example Explained

In an above example, we have three sets: seta, setb, and setc. The union() method is called on set1 and passed set2 and set3 as arguments to perform the union operation on all three sets. It returns setd, which contains all the unique elements from the three sets. Similarly, we can also use the | operator is used to achieve the same result.

Similarly, you can perform Union operation on more than three sets.


Share This Post!

Sets Union in Python

Leave a Reply

Your email address will not be published. Required fields are marked *