PYTHON
Perform Set Operations (Union, Intersection, Difference) in Python
Master fundamental set operations in Python to find common, unique, or combined elements between two sets, crucial for data comparison and filtering.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {3, 9}
# Union: Elements in either set1 or set2 or both
union_set = set1.union(set2)
# Alternatively: union_set = set1 | set2
print(f"Union of set1 and set2: {union_set}")
# Intersection: Elements common to both set1 and set2
intersection_set = set1.intersection(set2)
# Alternatively: intersection_set = set1 & set2
print(f"Intersection of set1 and set2: {intersection_set}")
# Difference: Elements in set1 but not in set2
difference_set1_2 = set1.difference(set2)
# Alternatively: difference_set1_2 = set1 - set2
print(f"Elements in set1 but not set2: {difference_set1_2}")
# Symmetric Difference: Elements in either set1 or set2 but not in both
symmetric_difference_set = set1.symmetric_difference(set2)
# Alternatively: symmetric_difference_set = set1 ^ set2
print(f"Elements in either set1 or set2 but not both: {symmetric_difference_set}")
# Check if one set is a subset or superset of another
is_subset = set3.issubset(set1)
is_superset = set1.issuperset(set3)
print(f"Is set3 a subset of set1? {is_subset}")
print(f"Is set1 a superset of set3? {is_superset}")
# Expected output:
# Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection of set1 and set2: {4, 5}
# Elements in set1 but not set2: {1, 2, 3}
# Elements in either set1 or set2 but not both: {1, 2, 3, 6, 7, 8}
# Is set3 a subset of set1? True
# Is set1 a superset of set3? True
How it works: Python's built-in `set` data type is highly optimized for membership testing and mathematical set operations. This snippet demonstrates common operations: `union()` (elements in either set), `intersection()` (elements common to both), `difference()` (elements in the first set but not the second), and `symmetric_difference()` (elements unique to each set). It also shows how to check for subset and superset relationships, providing efficient ways to compare and combine collections of unique items.