A set is an unordered collection of unique elements in Python. One of the built-in methods provided by Python for manipulating sets is the union()
method. The union()
method returns a new set containing all the distinct elements from two or more sets.
Syntax
set1.union(set2, set3, ...)
The union()
method takes one or more sets as arguments, separated by commas.
Return Value
The union()
method returns a new set containing all the distinct elements from the given sets.
Examples
Example 1: Using union() method to combine two sets
Let’s create two sets and use the union()
method to combine them:
# Create two sets set1 = {1, 2, 3} set2 = {3, 4, 5} # Use the union() method to combine the two sets set3 = set1.union(set2) # Print the combined set print(set3)
Output:
{1, 2, 3, 4, 5}
In the above example, we created two sets (set1
and set2
) and used the union()
method to combine them into a new set (set3
). The resulting set contains all the distinct elements from both sets.
Example 2: Using union() method with multiple sets
We can also use the union()
method with multiple sets:
# Create three sets set1 = {1, 2, 3} set2 = {3, 4, 5} set3 = {5, 6, 7} # Use the union() method to combine the three sets set4 = set1.union(set2, set3) # Print the combined set print(set4)
Output:
{1, 2, 3, 4, 5, 6, 7}
In the above example, we created three sets (set1
, set2
, and set3
) and used the union()
method to combine them into a new set (set4
). The resulting set contains all the distinct elements from all three sets.
Example 3: Using union() method with strings
We can also use the union()
method with strings:
# Create two sets of strings set1 = {'apple', 'banana', 'cherry'} set2 = {'orange', 'banana', 'kiwi'} # Use the union() method to combine the two sets set3 = set1.union(set2) # Print the combined set print(set3)
Output:
{'banana', 'kiwi', 'apple', 'cherry', 'orange'}
In the above example, we created two sets of strings (set1
and set2
) and used the union()
method to combine them into a new set (set3
). The resulting set contains all the distinct strings from both sets.
Use Cases
The union()
method is useful when we need to combine two or more sets into a single set containing all the distinct elements. This can be useful in many scenarios, such as:
- Combining data from multiple sources
- Eliminating duplicate entries in a set of data
- Creating a set of unique elements from multiple sets
Overall, the union()
method is a powerful tool for working with sets in Python.