PYTHON
Efficient Membership Test and Deduplication with Sets
Utilize Python sets for rapid O(1) average time complexity membership checks and to effortlessly remove duplicate elements from collections without preserving order.
# Membership testing
user_ids = {101, 102, 103, 104, 105}
if 103 in user_ids:
print("User 103 exists.")
# Deduplication
data_points = [1, 2, 2, 3, 4, 1, 5]
unique_data = list(set(data_points))
print(f"Original: {data_points}, Unique: {unique_data}")
# Set operations
active_users = {101, 103, 105}
premium_users = {102, 103, 106}
common_users = active_users.intersection(premium_users)
print(f"Users in both active and premium: {common_users}")
How it works: Python sets store only unique, hashable elements and provide highly optimized operations. The `in` operator offers average O(1) time complexity for membership checks, significantly faster than lists for large datasets. Converting a list to a set automatically removes duplicates; converting it back to a list gives a list of unique items (order not guaranteed). Sets also support powerful mathematical set operations like intersection, union, and difference.