Union() of Sets in Python
Union of Sets
The union() of two or more sets returns a set that contains all items from all the sets.
The result set contains distinct element that is if an item is present in more than one set, the result will contain only one appearance of this item.
∪ symbol denotes union of sets.
Union of Sets in Python
Let us understand this concept with an example, suppose there are two sets A and B, we have to find A ∪ B.
A = { 1 , 2, 3, 4, 5 }
B = { 1, 3, 5, 7, 9 }
A ∪ B = { 1, 2, 3, 4, 5, 7, 9 }
Syntax :
The parameter can be only one or more. You can compare as many sets as you like. Separate each set with a comma.
Return Type :
The union() method returns a new set with elements from the set and all other sets (passed as an argument).
If the argument is not passed to union(), it returns a shallow copy of the set.
Using the | operator
#union of sets using | operator
#example 1 set1 = {'P', 'Y', 'T', 'H', 'O', 'N' } set2 = {'C', 'O', 'D', 'I', 'N', 'G' } print( set1 | set2 ) #example 2 A = { 2, 4, 6, 8, 10, 11, 12 } B = { 3, 6, 9, 12, 15 } C = { 4, 8, 12, 16 } print( A | B | C )
Output : {'Y', 'T', 'N', 'D', 'G', 'I', 'C', 'P', 'H', 'O'} {2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16}
Using union() function
#union of sets using union() method #example 1 set1 = {'P', 'Y', 'T', 'H', 'O', 'N' } set2 = {'C', 'O', 'D', 'I', 'N', 'G' } print( set1.union(set2) ) #example 2 A = { 2, 4, 6, 8, 10, 11, 12 } B = { 3, 6, 9, 12, 15 } C = { 4, 8, 12, 16 } print( A.union(B,C) )
Output : {'Y', 'T', 'N', 'D', 'G', 'I', 'C', 'P', 'H', 'O'} {2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16}
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment