Python provides several set operations that you can use to perform different operations on sets. Here are some of the most commonly used set operations:
Union (| or union()): The union of two or more sets is a new set that contains all the unique elements from all the sets.
Example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
union_set = set1.union(set2, set3)
print(union_set) # Output: {1, 2, 3, 4, 5}
Intersection (& or intersection()): The intersection of two or more sets is a new set that contains only the common elements present in all the sets.
Example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
intersection_set = set1.intersection(set2, set3)
print(intersection_set) # Output: {3}
Difference (- or difference()): The difference between two sets is a new set that contains only the elements present in the first set but not in the second set.
Example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1}
Symmetric Difference (^ or symmetric_difference()): The symmetric difference between two sets is a new set that contains only the elements that are present in either of the sets, but not in both.
Example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 4}
Note that all these operations return a new set and do not modify the original sets.