PYTHON
Finding Common Elements Across Multiple Sets
Efficiently identify elements present in all of several Python sets using the `intersection` method, a powerful tool for data analysis and filtering across collections.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {3, 5, 7, 9, 10}
set4 = {5, 11, 12}
# Find elements common to set1 and set2
common_in_two = set1.intersection(set2)
print(f"Common in set1 and set2: {common_in_two}")
# Find elements common to all three sets using intersection method
common_in_three = set1.intersection(set2, set3)
print(f"Common in set1, set2, and set3: {common_in_three}")
# Find elements common to an arbitrary number of sets from a list
all_sets = [set1, set2, set3, set4]
# Using the * operator to unpack the list of sets into arguments for intersection
common_in_all = set.intersection(*all_sets)
print(f"Common in all sets: {common_in_all}")
# Alternative for two sets using the & operator (intersection operator)
common_alt_two = set1 & set2
print(f"Common in set1 & set2 (using & operator): {common_alt_two}")
How it works: Python's `set` data structure provides highly optimized methods for various set operations. The `intersection()` method (or the `&` operator for two sets) is used to find elements that are common to all specified sets. It can take multiple set arguments, allowing you to easily find the common elements across an arbitrary number of sets. This approach is significantly more efficient than manually iterating and checking membership, especially for large datasets, due to the underlying hash-table implementation of sets.