search

What is the use of the "union" function in Python?

In Python, the union() function is used to perform the union operation on sets. The union of two or more sets is a new set that contains all the unique elements from the participating sets. The union() function can take one or more sets as arguments and returns a new set that is the union of all the sets. Here's an example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {5, 6, 7}

union_set = set1.union(set2, set3)
print(union_set)  # Output: {1, 2, 3, 4, 5, 6, 7}

In this example, the union() function is used to compute the union of set1, set2, and set3. The resulting set union_set contains all the unique elements from these sets.

The union() function can also be invoked using the pipe operator (|) as a shorthand notation:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {5, 6, 7}

union_set = set1 | set2 | set3
print(union_set)  # Output: {1, 2, 3, 4, 5, 6, 7}

Both approaches produce the same result: a new set that contains all the elements from the participating sets, with duplicates removed.

The union() function is useful when you need to combine multiple sets and obtain a single set containing all the unique elements. It can be particularly handy for set operations such as merging data, finding the combined set of values, or performing set comparisons.

Related Questions You Might Be Interested