Sets, Membership, and Duplicate Values
A set stores membership under an equality rule and does not retain a separate entry for every occurrence.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Track distinct names
Constructing a Python set from tea, rice, and tea gives two elements. A membership test for tea returns true. The set does not store whether tea appeared once or twice. Use frequency counts when multiplicity matters.
Keep required order separately
Do not rely on the iteration order of a Python set to reproduce the source order. For a report with distinct first occurrences, keep a result sequence and use the set only as the record of seen keys. See deduplication in input order.[1]
Trace what is lost by collapsing equal values
A collection of visit labels [west, east, west, north] has four events and three distinct labels. The predicate “has any west visit” can use a set, but computing visit totals needs multiplicities. Converting to a set before counting changes the answer for west from two to one. A pair of different events with the same region still represents two visits. See dictionary frequency counts.
Select identifiers before adding objects
If events are mutable records, use an immutable event identifier as the set key. A key made from the region alone would collapse events from the same region. Two deliveries of the same event can intentionally share a key if the task is deduplication. Test equal values from different events and duplicate deliveries of one event. If input order must survive, retain an output sequence alongside membership. See deduplication in input order.