PYTHON
Perform Efficient Set Operations (Union, Intersection, Difference) on Python Lists
Utilize Python sets to quickly find unique elements, common items, or differences between two lists, leveraging built-in set operations for efficiency.
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Convert lists to sets for efficient operations
set1 = set(list1)
set2 = set(list2)
# Union: All unique elements from both sets
union_set = set1.union(set2) # or set1 | set2
print(f"List 1: {list1}")
print(f"List 2: {list2}")
print(f"Union (all unique elements): {list(union_set)}")
# Intersection: Elements common to both sets
intersection_set = set1.intersection(set2) # or set1 & set2
print(f"Intersection (common elements): {list(intersection_set)}")
# Difference: Elements in set1 but not in set2
difference_set = set1.difference(set2) # or set1 - set2
print(f"Difference (elements in List1 but not List2): {list(difference_set)}")
# Symmetric Difference: Elements in either set, but not in both
symmetric_difference_set = set1.symmetric_difference(set2) # or set1 ^ set2
print(f"Symmetric Difference (unique to each list): {list(symmetric_difference_set)}")
How it works: Python's `set` data structure is highly optimized for membership testing and mathematical set operations. By converting lists into sets, you can efficiently perform operations like finding the `union` (all unique elements from both), `intersection` (elements common to both), `difference` (elements in the first set but not the second), and `symmetric_difference` (elements unique to each set, excluding common ones). These operations are much faster on sets than iterating through lists, especially for large datasets, and are invaluable for data comparison and filtering tasks.