PYTHON
Efficiently Handling Unique Elements and Set Operations
Learn to use Python sets for quickly finding unique items, performing unions, intersections, and differences on data collections with optimal performance.
# Creating a set from a list to get unique elements
data = [1, 2, 2, 3, 4, 4, 5]
unique_elements = set(data)
print(f"Unique elements: {unique_elements}")
# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union: elements in A or B or both
union_set = set_a.union(set_b)
print(f"Union (A | B): {union_set}")
# Intersection: elements in both A and B
intersection_set = set_a.intersection(set_b)
print(f"Intersection (A & B): {intersection_set}")
# Difference: elements in A but not in B
difference_set = set_a.difference(set_b)
print(f"Difference (A - B): {difference_set}")
# Symmetric Difference: elements in A or B but not in both
symmetric_difference_set = set_a.symmetric_difference(set_b)
print(f"Symmetric Difference (A ^ B): {symmetric_difference_set}")
# Checking for membership (average O(1) time complexity)
print(f"Is 3 in set_a? {3 in set_a}")
print(f"Is 7 in set_b? {7 in set_b}")
How it works: Python sets are unordered collections of unique items. They are highly optimized for membership testing (average O(1) time complexity) and mathematical set operations like union, intersection, and difference. This makes them ideal for tasks requiring uniqueness or efficient comparison between collections of items, such as filtering duplicate entries or comparing user groups.