PYTHON
Efficient Deduplication and Set Operations with Python Sets
Learn to use Python sets for lightning-fast deduplication of lists, efficient membership testing, and performing powerful set operations like union, intersection, and difference.
# Deduplicate a list
data = [1, 2, 2, 3, 4, 4, 5, 1]
unique_elements = list(set(data))
print(f"Deduplicated list: {unique_elements}")
# Membership testing (O(1) average time complexity)
my_set = {10, 20, 30, 40}
print(f"Is 20 in set? {20 in my_set}")
print(f"Is 50 in set? {50 in my_set}")
# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
union_set = set_a.union(set_b) # Elements in either set_a or set_b
print(f"Union: {union_set}")
intersection_set = set_a.intersection(set_b) # Elements common to both
print(f"Intersection: {intersection_set}")
difference_set = set_a.difference(set_b) # Elements in set_a but not in set_b
print(f"Difference (A - B): {difference_set}")
symmetric_difference_set = set_a.symmetric_difference(set_b) # Elements in either but not both
print(f"Symmetric Difference: {symmetric_difference_set}")
How it works: Python `set` is an unordered collection of unique elements. It's highly efficient for tasks like removing duplicates from a list, checking for element existence (membership testing), and performing mathematical set operations such as union, intersection, and difference. This snippet demonstrates these common uses, providing a fast way to process and analyze collections of items.