PYTHON
Efficient Unique Element Management with Python Sets
Leverage Python sets for lightning-fast membership testing, eliminating duplicates, and performing mathematical set operations like union and intersection efficiently.
# Basic set creation and removing duplicates from a list
my_list = [1, 2, 2, 3, 4, 4, 5, 1, 6]
unique_elements = set(my_list)
print(f"Original list: {my_list}")
print(f"Unique elements (set): {unique_elements}") # Output: {1, 2, 3, 4, 5, 6} (order not guaranteed)
# Fast membership testing (average O(1) time complexity)
print(f"Is 3 in the set? {3 in unique_elements}") # Output: True
print(f"Is 7 in the set? {7 in unique_elements}") # Output: False
# Adding and removing elements
unique_elements.add(7)
print(f"Set after adding 7: {unique_elements}")
unique_elements.discard(1) # Removes 1 if present, does nothing if not
print(f"Set after discarding 1: {unique_elements}")
# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(f"
Set A: {set_a}")
print(f"Set B: {set_b}")
# Union: all unique elements from both sets
print(f"Union (A | B): {set_a.union(set_b)}") # or set_a | set_b
# Intersection: common elements in both sets
print(f"Intersection (A & B): {set_a.intersection(set_b)}") # or set_a & set_b
# Difference: elements in A but not in B
print(f"Difference (A - B): {set_a.difference(set_b)}") # or set_a - set_b
# Symmetric Difference: elements in A or B, but not both
print(f"Symmetric Difference (A ^ B): {set_a.symmetric_difference(set_b)}") # or set_a ^ set_b
# Check for subsets and supersets
set_c = {1, 2}
print(f"Is C a subset of A? {set_c.issubset(set_a)}")
print(f"Is A a superset of C? {set_a.issuperset(set_c)}")
How it works: Python's built-in `set` data type stores only unique, immutable elements and provides highly optimized operations for membership testing (checking if an element is present), which typically takes O(1) average time complexity. Sets are also fundamental for performing mathematical set operations such as union (combining elements), intersection (finding common elements), difference (elements in one set but not another), and symmetric difference (elements in either set but not both). They are ideal for efficiently managing collections of unique items and performing comparisons between them.