PYTHON
Efficient Set Operations (Union, Intersection, Difference) in Python
Master Python's built-in set data structure for fast membership testing, removing duplicates, and performing efficient mathematical set operations like union, intersection, and difference.
# Define two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(f"Set 1: {set1}")
print(f"Set 2: {set2}")
# Union: Elements in either set1 OR set2
union_set = set1.union(set2) # or set1 | set2
print(f"Union (set1 | set2): {union_set}")
# Intersection: Elements common to BOTH set1 AND set2
intersection_set = set1.intersection(set2) # or set1 & set2
print(f"Intersection (set1 & set2): {intersection_set}")
# Difference: Elements in set1 BUT NOT in set2
difference_set = set1.difference(set2) # or set1 - set2
print(f"Difference (set1 - set2): {difference_set}")
# Symmetric Difference: Elements in EITHER set1 OR set2, but NOT in both
symmetric_difference_set = set1.symmetric_difference(set2) # or set1 ^ set2
print(f"Symmetric Difference (set1 ^ set2): {symmetric_difference_set}")
# Check for subsets and supersets
set_a = {1, 2}
set_b = {1, 2, 3}
print(f"Is set_a a subset of set_b? {set_a.issubset(set_b)}") # or set_a <= set_b
print(f"Is set_b a superset of set_a? {set_b.issuperset(set_a)}") # or set_b >= set_a
How it works: Python's `set` is an unordered collection of unique elements. It's highly optimized for membership testing (`in` operator) and for performing standard mathematical set operations. These operations (union, intersection, difference, symmetric difference) are very efficient, typically running in O(len(set1) + len(set2)) time, making sets ideal for tasks like finding common tags, distinct user IDs, or filtering unique elements from collections.