PYTHON
Leveraging Python Sets for Duplicate Removal and Comparisons
Discover how Python sets provide efficient ways to remove duplicate items from lists, perform quick membership checks, and execute common set operations like union and intersection.
# 1. Removing duplicates from a list
data_with_duplicates = [1, 2, 2, 3, 4, 4, 5, 1]
unique_data = list(set(data_with_duplicates))
print(f"Original: {data_with_duplicates}")
print(f"Unique data: {unique_data}")
# 2. Fast membership testing
my_set = {10, 20, 30, 40}
print(f"Is 20 in my_set? {20 in my_set}")
print(f"Is 50 in my_set? {50 in my_set}")
# 3. Set operations: Union, Intersection, Difference
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union: all unique elements from both sets
union_set = set_a.union(set_b) # or set_a | set_b
print(f"Union (A | B): {union_set}")
# Intersection: common elements in both sets
intersection_set = set_a.intersection(set_b) # or set_a & set_b
print(f"Intersection (A & B): {intersection_set}")
# Difference: elements in A but not in B
difference_set_ab = set_a.difference(set_b) # or set_a - set_b
print(f"Difference (A - B): {difference_set_ab}")
# Symmetric Difference: elements in either A or B, but not in both
symmetric_difference_set = set_a.symmetric_difference(set_b) # or set_a ^ set_b
print(f"Symmetric Difference (A ^ B): {symmetric_difference_set}")
How it works: Python sets are unordered collections of unique elements, making them ideal for tasks involving uniqueness, membership testing, and mathematical set operations. This snippet illustrates how to efficiently remove duplicate items from a list by converting it to a set and back. It also demonstrates fast O(1) average-case membership testing (checking if an element exists in the set). Furthermore, it showcases common set operations like union (combining all unique elements), intersection (finding common elements), difference (elements unique to the first set), and symmetric difference (elements unique to either set).