DSA Hash Sets in Python
A hash set is a collection of distinct values that answers membership questions in one step. Python's set is a hash set.
Duplicates collapse
Repeated values enter the set only once. Sorting makes the printed order stable.
seen = {3, 1, 3, 2, 1}
print(len(seen))
print(sorted(seen))Ask about membership
The in operator asks whether a value is present. The answer is True or False.
places = {"gate", "path", "well"}
print("path" in places)
print("lake" in places)Add and remove
The add method inserts one value. The remove method deletes one value.
tags = {"red", "blue"}
tags.add("green")
tags.remove("red")
print(sorted(tags))Example
values = [8, 3, 5, 3, 9, 5, 2]
seen = set()
checked = 0
for index, value in enumerate(values):
checked += 1
if value in seen:
print("first repeat:", value)
print("position:", index)
break
seen.add(value)
print("values checked:", checked)Key points
- A set stores each distinct value exactly once.
- Adding a value already present changes nothing.
- A membership test goes straight to one bucket.
- A set has no positions and no index numbers.
- Printing a set in sorted order keeps the output stable.
In this example, the loop adds each new value to the set. The value 3 is already present at position 3. The search stops at that first repeat. Only four values were checked before the stop.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
A list is [4, 4, 6, 6, 6, 9]. How many values does a set built from it hold?