PYTHON
Performing Efficient Set Operations in Python
Discover how to leverage Python's built-in set data structure for blazing-fast membership testing, duplicate removal, and mathematical set operations like union, intersection, and difference in your web applications.
# Example data: lists of user IDs
active_users = {101, 102, 103, 104, 105}
premium_users = {103, 105, 106, 107}
new_signups = {105, 108, 109}
# 1. Union: All unique users from active or premium
all_users = active_users.union(premium_users)
# print(f"All unique users: {all_users}")
# Expected: {101, 102, 103, 104, 105, 106, 107}
# 2. Intersection: Users who are both active and premium
active_and_premium = active_users.intersection(premium_users)
# print(f"Active and Premium users: {active_and_premium}")
# Expected: {103, 105}
# 3. Difference: Users who are active but not premium
active_only = active_users.difference(premium_users)
# print(f"Active only users: {active_only}")
# Expected: {101, 102, 104}
# 4. Symmetric Difference: Users in either set, but not both
either_but_not_both = active_users.symmetric_difference(premium_users)
# print(f"Users in either set, but not both: {either_but_not_both}")
# Expected: {101, 102, 104, 106, 107}
# 5. Membership testing (O(1) average time complexity)
user_id_to_check = 101
is_active = user_id_to_check in active_users
# print(f"Is user {user_id_to_check} active? {is_active}")
# Expected: True
# 6. Removing duplicates from a list
data_with_duplicates = [1, 2, 2, 3, 1, 4, 5, 5, 6]
unique_data = list(set(data_with_duplicates))
# print(f"Unique data: {unique_data}")
# Expected: [1, 2, 3, 4, 5, 6] (order not guaranteed)
How it works: Python's `set` is an unordered collection of unique elements, providing highly efficient operations for membership testing (checking if an item exists) and mathematical set operations. This snippet demonstrates `union` (elements in either set), `intersection` (elements common to both), `difference` (elements in the first but not the second), `symmetric_difference` (elements in either but not both), and how to efficiently remove duplicates from a list.