PYTHON
Efficient Set Operations for Unique Elements and Membership Tests
Optimize your Python code with sets for fast membership testing, removing duplicates, and performing common mathematical set operations.
# Creating sets
my_set = {1, 2, 3, 2, 1}
print(f"Set from list with duplicates: {my_set}") # Duplicates are removed automatically
# Adding elements
my_set.add(4)
print(f"Set after adding 4: {my_set}")
# Fast membership testing (average O(1) complexity)
print(f"Is 2 in my_set? {2 in my_set}")
print(f"Is 5 in my_set? {5 in my_set}")
# 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) # or set_a | set_b
print(f"Union of A and B: {union_set}")
# Intersection (elements in both A and B)
intersection_set = set_a.intersection(set_b) # or set_a & set_b
print(f"Intersection of A and B: {intersection_set}")
# Difference (elements in A but not in B)
difference_set = set_a.difference(set_b) # or set_a - set_b
print(f"Difference (A - B): {difference_set}")
# Symmetric Difference (elements in A or B but not both)
symmetric_difference_set = set_a.symmetric_difference(set_b) # or set_a ^ set_b
print(f"Symmetric Difference: {symmetric_difference_set}")
# Checking for subset/superset
subset_test = {1, 2}
print(f"Is {subset_test} a subset of {set_a}? {subset_test.issubset(set_a)}") # or subset_test <= set_a
print(f"Is {set_a} a superset of {subset_test}? {set_a.issuperset(subset_test)}") # or set_a >= subset_test
How it works: Python `set` objects are unordered collections of unique elements, providing highly efficient operations for membership testing (checking if an item exists) and mathematical set operations like union, intersection, and difference. They are ideal for tasks such as removing duplicates from a list, quickly checking for existing items (e.g., user permissions, visited IDs), or managing unique tags. This snippet covers common set creation and manipulation techniques.