Skip to content

Sets and membership

A set stores distinct hashable values. Use a Python set when the question asks whether a value exists and does not need its position or frequency. Repeated insertion preserves one member. Sets have no insertion-order guarantee, so their iteration order must not determine an answer.

The examples use invented integer sequences. Read hash maps to compare membership with frequency counts.

Create an empty set with set(). The literal {} creates an empty dictionary. discard tolerates an absent value, while remove raises KeyError when the value is absent.

seen: set[int] = set()
for value in [4, 1, 4, 2, 1]:
duplicate = value in seen
seen.add(value)
print("Read:", value, "Duplicate:", duplicate, "Members:", sorted(seen))
seen.discard(9)
seen.remove(2)
print("After removals:", sorted(seen))
print("Intersection:", sorted(seen & {1, 3, 4}))
print("Difference:", sorted(seen - {1}))
Read: 4 Duplicate: False Members: [4]
Read: 1 Duplicate: False Members: [1, 4]
Read: 4 Duplicate: True Members: [1, 4]
Read: 2 Duplicate: False Members: [1, 2, 4]
Read: 1 Duplicate: True Members: [1, 2, 4]
After removals: [1, 4]
Intersection: [1, 4]
Difference: [4]

The example sorts members only to produce a readable display. That display order is not a property of the set. Choose a dictionary when you must retain counts, or a list when positions and duplicates belong to the answer.

A collection contains integer checkpoint numbers in arbitrary order. Find the length of its longest run of consecutive integers. Duplicates do not extend a run. For example, [8, 3, 5, 4, 3, 10] contains the consecutive checkpoint values 3, 4, and 5.

Sorting gives a valid O(n log n) approach. A set lets the algorithm start a scan only when a value has no predecessor. Every later value in that run belongs to the same start.

def longest_consecutive(values: list[int]) -> int:
"""Find the length of the longest run of consecutive integers.
Args:
values: Unsorted integers, possibly with duplicates.
Returns:
The maximum run length, or zero for an empty input.
"""
members = set(values)
longest = 0
for start in members:
if start - 1 in members:
continue
end = start
while end in members:
end += 1
longest = max(longest, end - start)
return longest
checkpoints = [8, 3, 5, 4, 3, 10]
members = set(checkpoints)
for start in sorted(members):
if start - 1 in members:
print("Skip non-start:", start)
continue
run = []
current = start
while current in members:
run.append(current)
current += 1
print("Run from:", start, "Members:", run)
print("Longest length:", longest_consecutive(checkpoints))
Run from: 3 Members: [3, 4, 5]
Skip non-start: 4
Skip non-start: 5
Run from: 8 Members: [8]
Run from: 10 Members: [10]
Longest length: 3

At the start of an inner loop iteration, every integer from start through end - 1 belongs to the set. The first absent end closes that consecutive run. Every run has one smallest member, so the algorithm considers every run exactly once.

Let n be the number of input values and u the number of distinct values. The set uses O(u) auxiliary space. Set membership and insertion take expected O(1) time for ordinary hash distributions and fixed-size values. Hash collisions can make an individual operation O(u).

The outer loop visits each distinct value once. Across all inner loops, each distinct value appears in only one run, so the expected total time is O(n). Two nested loops do not imply O(n²) when their combined work is bounded this way. The hash-collision worst case can still take O(n²). The sorted trace is a separate O(u log u) display step.

assert longest_consecutive([]) == 0
assert longest_consecutive([6, 6, 6]) == 1
assert longest_consecutive([-2, 0, -1, 5]) == 3
assert longest_consecutive([1, 3, 5]) == 1
assert longest_consecutive([4, 3, 2, 1]) == 4
print("Boundary checks passed.")
Boundary checks passed.

Download the Python source to run the complete example locally.

Python’s set documentation defines membership, set operations, and the absence of ordering guarantees. It also distinguishes mutable sets from frozenset.

The Python data structures tutorial introduces set construction and duplicate removal. Use it to compare the available operations with dictionary operations.

CPython’s set implementation describes its hash-table lookup strategy. It explains why collision behavior belongs in a precise complexity discussion.