![]() |
VOOZH | about |
Sets are a fundamental data structure in Python that store unique elements. Python provides built-in operations for performing set operations such as union, intersection, difference and symmetric difference. In this article, we understand these operations one by one.
The union of two sets combines all unique elements from both sets.
Syntax:
set1 | set2 # Using the '|' operator
set1.union(set2) # Using the union() method
Example:
using '|': {1, 2, 3, 4, 5, 6}
using union(): {1, 2, 3, 4, 5, 6}
Explanation: | operator and union() method both return a new set containing all unique elements from both sets .
The intersection of two sets includes only the common elements present in both sets.
Syntax:
set1 & set2 # Using the '&' operator
set1.intersection(set2) # Using the intersection() method
Example:
using '&': {3, 4}
using intersection(): {3, 4}
Explanation: & operator and intersection() method return a new set containing only elements that appear in both sets.
The difference between two sets includes elements present in the first set but not in the second.
Syntax:
set1 - set2 # Using the '-' operator
set1.difference(set2) # Using the difference() method
using '-': {1, 2}
using difference(): {1, 2}
Explanation: - operator and difference() method return a new set containing elements of A that are not in B.
The symmetric difference of two sets includes elements that are in either set but not in both.
Syntax:
set1 ^ set2 # Using the '^' operator
set1.symmetric_difference(set2) # Using the symmetric_difference() method
Example:
using '^': {1, 2, 5, 6}
using symmetric_difference(): {1, 2, 5, 6}
Explanation:^ operator and symmetric_difference() method return a new set containing elements that are in either A or B but not in both.