DSA Hash Sets
A hash set is a hash table specialized to store unique elements with no associated values, giving near-instant membership tests via Python's built-in set.
What Is a Hash Set?
A hash set stores a collection of distinct elements with no guaranteed order. Internally it is a hash table where each bucket holds only the key - there is no value paired with it - so a set answers exactly one question extremely fast: is this element already in here?
Creating and Using Sets in Python
Example
fruits = {'apple', 'banana', 'cherry'}
fruits.add('date')
fruits.add('apple') # duplicate, ignored silently
fruits.remove('banana')
print(fruits) # order not guaranteed
print(len(fruits)) # 3
print('cherry' in fruits) # TrueMembership Testing and Set Operations
Checking whether an element exists in a Python list requires scanning every item in the worst case, which is O(n). A set computes the element's hash and jumps straight to its bucket, making membership tests O(1) on average regardless of how many elements the set holds. This is why sets are the go-to structure for deduplication, lookups, and filtering large collections.
- union(other) or | - every element that appears in either set
- intersection(other) or & - only the elements common to both sets
- difference(other) or - - elements in the first set but not the second
- symmetric_difference(other) or ^ - elements in exactly one of the two sets
Example
python_devs = {'Ada', 'Grace', 'Linus'}
java_devs = {'Linus', 'James', 'Grace'}
print(python_devs | java_devs) # union
print(python_devs & java_devs) # intersection
print(python_devs - java_devs) # difference
print(python_devs ^ java_devs) # symmetric differenceExample
numbers = [4, 2, 4, 7, 2, 9, 4]
unique_numbers = list(set(numbers))
print(sorted(unique_numbers)) # [2, 4, 7, 9]
# Order-preserving alternative
ordered_unique = list(dict.fromkeys(numbers))
print(ordered_unique) # [4, 2, 7, 9]