Python Set union() method
Python Set union() method
The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets.
Syntax
set.union(set1, set2...)
Parameter
set1- This parameter represents the first set to search for equal items
set2- This argument signifies the other set to search for equal items.
One can compare as many sets as needed, only need to separate the sets with a comma.
Return
This method returns a new set with distinct elements from all the sets and writing the common elements between both the sets only once.
Example 1
# Python program explaining # the set.union() method # initializing the set1 set1 = {1,2,3,4,5,6} # printing the actual set 1 print("Set 1:",set1) # initializing the set2 set2 = {2,7,8,6,5} # printing the actual set 2 print("Set 2:",set2) # returns a new set with different items from all the sets and #writing the common elements between both the sets only once Union= set1.union(set2) print("A U B: ",Union)
Output
Set 1: {1, 2, 3, 4, 5, 6} Set 2: {8, 2, 5, 6, 7} A U B: {1, 2, 3, 4, 5, 6, 7, 8}
Example 2
# Python program explaining # the set.union() method # initializing a list of fruits A = {'apple', 'watermelon', 'mango','guava','orange','Lichi'} # initializing the summer fruits B = {'Mushmelon', 'watermelon', 'mango','Blueberry'} # initializing the specifically the winter fruits C= {'apple','guava','orange','Grapes'} # will return the unique elements in both the sets print('A U B =', A.union(B)) print('B U C =', B.union(C)) #passing two set parameters in the union method # will return the unique items from all the sets print('A U B U C =', A.union(B, C)) # passing only one argument print('A.union() = ', A.union())
Output
A U B = {'mango', 'apple', 'watermelon', 'Mushmelon', 'orange', 'Lichi', 'guava', 'Blueberry'} B U C = {'mango', 'Mushmelon', 'apple', 'orange', 'guava', 'Grapes', 'watermelon', 'Blueberry'} A U B U C = {'mango', 'apple', 'Mushmelon', 'orange', 'Lichi', 'guava', 'Grapes', 'watermelon', 'Blueberry'} A.union() = {'mango', 'apple', 'watermelon', 'orange', 'Lichi', 'guava'}
Example 3
# Python program explaining # the set.union() method A = {1,2,3,4,5,6} B = {2,4,6,8 } print("Printing the union by two different method>>>") # the operator '|' is used to get the union for two sets print("By '|' operator\n A U B:", A | B) # using the set.union() method print("Bu using the set.union() method\n A U B:",A.union(B))
Output
Printing the union by two different method>>> By '|' operator A U B: {1, 2, 3, 4, 5, 6, 8} Bu using the set.union() method A U B: {1, 2, 3, 4, 5, 6, 8}