Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python sets: membership and deduplication do not preserve input order

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A set retains distinct hashable values and supports membership and set operations.

Download Python source kit

Operation contract

The delivery fixture finds identifiers already processed and identifiers still pending. It sorts the results solely to make the displayed output deterministic; the set itself has no promised input order. Set membership is useful when deciding whether a duplicate has already been seen, but it removes multiplicity information.

Failure and ownership boundary

If two identical receipt IDs indicate two separate rejected events, a set of IDs cannot tell how often the failure happened. Use a counter or retained events when frequency is part of the question. Python collection exercise: reject repeated receipt IDs before committing state and Python heapq top-k: define ties before ranking frequencies select different evidence.

Working program

python
received_ids = {41, 42, 43}
processed_ids = {41, 44}
print(sorted(received_ids & processed_ids))
print(sorted(received_ids - processed_ids))
print(len({41, 41, 42}))

Output

Output
[41]
[42, 43]
2

Costs and limits

Expected membership has constant hash-table work for ordinary keys; retaining n distinct values takes O(n) storage. Sorting k displayed IDs adds O(k log k) time and output storage.

Common Mistakes

  • Do not promise input order from a set.
  • Deduplication loses frequency.

Connected lessons

Python dictionaries: insertion order and duplicate-key replacement, Python collection exercise: reject repeated receipt IDs before committing state, Python heapq top-k: define ties before ranking frequencies.

python
sets
Storage details