Data structures: order, identity and the cost of stale work
AI 常用数据结构
Choose containers by their operations, then build and verify a versioned priority queue with explicit cancellation and memory costs.
data-structuresChoose the operation before the container
An indexing service has three pending jobs. One job becomes urgent; another is cancelled. “Store the jobs in a list” is easy. “Always take the most urgent current job, with predictable ties” is a more useful specification.
A data structure combines a representation with operations that preserve its rules. A queue is an interface: take items in arrival order. A priority queue is a different interface: take the smallest or largest priority. Neither interface requires a particular Python container. The MIT data-structures lecture separates the operations an interface promises from the representation used to implement them.
We will build one small priority queue using a heap and a dictionary, then use a bounded deque for recent history. Each container has a separate job. The example schedules labels; it does not launch processes or connect to an indexing service.
Order, identity and validity are different rules
Common choices in Python
| Need | Useful structure | What to remember |
|---|---|---|
| Read item i; append a batch result | list | Indexing is constant time in the usual array model; middle/front changes move references. |
| Keep a fixed record of fields | tuple | Its slots cannot be reassigned; an object inside a slot may still be mutable. |
| Track whether an ID has appeared | set | Stores membership, not a meaningful sorted order. Keys must be hashable. |
| Map an ID to its current record | dict | Keys are unique; insertion order is not priority order. |
| Add and remove at both ends | deque | Good for FIFO work; arbitrary middle access is not its strength. |
| Repeatedly extract a minimum | heapq over a list | Only the root is guaranteed to be minimal; the list is not fully sorted. |
A Python list stores references to objects; it is not the same thing as a packed numerical tensor. A tuple containing a list is not a deeply frozen record and cannot be used as a dictionary key. More generally, hashability requires a stable hash consistent with equality, not merely a type name that sounds immutable. In the example, IDs are nonempty strings, priorities are integers, and queue entries contain only these values and a sequence number. Python data-structures tutorial
List append and end pop have amortized constant cost in the dynamic-array model. That means occasional expensive resizing is spread over a sequence of operations; it does not promise constant latency for each call. For a simple doubling design, all copied capacities before reaching N items obey:
Together with N ordinary writes, this gives linear total work over N appends. The doubling argument explains amortization; it is not a claim that CPython uses exactly that growth factor. Repeated pop(0) on a list shifts the remaining elements and can take quadratic total work. A deque supports efficient end operations; a full deque(maxlen=k) discards old items from the opposite end when new items are appended. That makes it suitable for a short history, not for pending work that must never be dropped. MIT notes, deque documentation
A heap orders entries; a dictionary identifies the current version
For a zero-indexed min-heap, each existing child is no smaller than its parent:
Following parent links proves that the root is a minimum. Removing that root and restoring the invariant takes logarithmically many heap comparisons. The invariant does not order siblings or unrelated branches. Python’s heapify builds a heap in linear time, whereas inserting every element separately has a logarithmic factor in its general upper bound. heapq documentation
Our heap entries are (priority, serial, ID). Lower priorities run first. Every successful put gets a new serial, including a replacement with the same priority. Thus a replacement goes behind already-pending jobs with that priority. Serials never repeat within a queue, so heap comparisons never need to compare IDs after equal priorities and serials.
The dictionary A holds one current (priority, serial) pair per active ID. A heap entry is live exactly when it matches that pair:
Updating an ID inserts a fresh entry and changes A; the old heap entry becomes stale. Cancelling removes the dictionary entry. We do not search the heap to delete an arbitrary item, and we do not mutate a priority in place, which could break the heap invariant.
Why is extraction correct? Every active record has exactly one matching heap entry. pop repeatedly removes the heap minimum and discards stale versions. When it finds a live entry, no smaller live entry can remain: such an entry would have preceded it in the heap’s extraction order. If the heap is exhausted, no active record remains. Compaction preserves the same live entries and serials, so it preserves future results. The official heap documentation discusses the same general priority-update problem; the version-matching implementation below uses immutable entries instead of marking a mutable entry as removed.
A current-record table beside the heap
Run this complete program with Python 3.12. put returns the new serial. cancel returns whether a live ID was removed. pop returns (ID, priority, serial) or None; it never returns a stale version. sizes reports live records first, physically stored heap entries second. compact rebuilds both containers and returns the number of discarded heap entries. Input validation occurs before changing state. The underscored containers are internal; mutating them externally would void the invariants.
import heapq
from collections import deque
class WorkQueue:
"""Single-threaded queue; lower integer priorities run first."""
def __init__(self):
self._heap = []
self._active = {}
self._next = 0
@staticmethod
def _key(key):
if type(key) is not str or not key:
raise ValueError('task ID must be a nonempty string')
def put(self, key, priority):
self._key(key)
if type(priority) is not int:
raise ValueError('priority must be an integer, not bool')
serial = self._next
self._next += 1
self._active[key] = (priority, serial)
heapq.heappush(self._heap, (priority, serial, key))
return serial
def cancel(self, key):
self._key(key)
return self._active.pop(key, None) is not None
def pop(self):
while self._heap:
priority, serial, key = heapq.heappop(self._heap)
if self._active.get(key) == (priority, serial):
del self._active[key]
return key, priority, serial
return None
def compact(self):
old_size = len(self._heap)
active = {key: entry for key, entry in self._active.items()}
heap = [(priority, serial, key)
for key, (priority, serial) in active.items()]
heapq.heapify(heap)
self._active, self._heap = active, heap
return old_size - len(heap)
def sizes(self):
return len(self._active), len(self._heap)
def main():
queue = WorkQueue()
history = deque(maxlen=2)
queue.put('embed', 4)
queue.put('index', 2)
queue.put('rerank', 2)
queue.put('embed', 1)
print('live / stored:', queue.sizes())
print('cancel index:', queue.cancel('index'))
print('removed by compaction:', queue.compact())
while (task := queue.pop()) is not None:
history.append(task)
print('completed:', tuple(history))
print('empty:', queue.pop(), queue.sizes())
queue.put('first', 5)
queue.put('second', 5)
queue.put('first', 5)
print('replacement tie:', queue.pop(), queue.pop())
history.append(('later', 0, 99))
print('bounded history:', tuple(history))
print('cancel missing:', queue.cancel('missing'))
if __name__ == '__main__':
main()
Output:
live / stored: (3, 4)
cancel index: True
removed by compaction: 2
completed: (('embed', 1, 3), ('rerank', 2, 2))
empty: None (0, 0)
replacement tie: ('second', 5, 5) ('first', 5, 6)
bounded history: (('rerank', 2, 2), ('later', 0, 99))
cancel missing: False
Initially three jobs are live but four entries are stored, because embed has two versions. After cancelling index, compaction discards two stale entries. In the later tie, first was replaced after second, so second runs first. The history deque deliberately keeps only its two newest records.
Account for stored work, not just live jobs
Let H be the physical heap length and L the live dictionary size. Under expected constant-time hash lookup and constant-time integer comparisons, put uses O(log(H+2)) heap comparisons; its list-allocation cost is amortized. cancel uses expected constant dictionary work. A pop that removes t stale entries before one live entry uses O(1+(t+1)*log(H+1)) comparisons. An individual call may drain the entire stale heap, even when L is zero. Over a sequence, each inserted heap entry is extracted at most once or discarded by compaction.
Compaction’s new list construction and heapify cost O(1+L). That is not the whole Python operation: the old heap must be released, and a dictionary can retain allocated capacity after deletions. If P is the dictionary’s physical storage that must be scanned or released, this implementation costs O(1+H+P+L) for compaction, with O(1+H+P+L) transient storage slots while rebuilding. Without compaction, memory follows retained heap entries and dictionary capacity, not just L. As a simple conservative bound, both are at most linear in the number of submissions since creation.
These are container-operation bounds. Hashing a long new string, comparing very large integers, allocation and object storage add their own costs. Hash-table constant-time behavior is conditional on hashing and load assumptions; collisions can make lookup linear in the table’s entries. No timing benchmark is needed to establish that repeatedly updating one live job can leave many stale records.
The interface should expose its tradeoffs
Lazy deletion trades cheap cancellation for deferred cleanup and memory. It is useful when extraction or periodic compaction will reclaim old entries. It is a poor default if a service needs a strict bound on the latency of every extraction. An indexed heap can support direct updates, but it must maintain an additional ID-to-position invariant through every swap.
This queue is single-threaded and in memory. Several container operations together are not one atomic transaction, even if an individual built-in operation happens to be safe under a particular interpreter. It has no persistence, fairness guarantee between different priorities, retry policy or task execution. A stream of urgent submissions can delay a low-priority job indefinitely.
Container choice also affects semantics. A set discards multiplicity; a dictionary replacement discards the old value unless another structure keeps it; a bounded deque silently forgets old history on append. Decide whether duplicate IDs mean a replacement, a repeated observation or a distinct task before choosing a key. The example chooses replacement and states its tie rule explicitly.
Predict the next operation
- Live does not mean stored. Start empty, update the same ID ten times, then cancel it. What are the two sizes before extraction or compaction?
Count versions separately
Answer: There are zero live records and ten stored heap entries: (0,10). Each successful put inserted one version; cancellation removed only the current dictionary entry. pop can then discard all ten entries before returning None.
- Read the tie rule. Submit A with priority 3, submit B with priority 3, then replace A with priority 3. Which runs first?
Use the current serial
Answer: B runs first. A’s replacement has a newer serial and its original entry is stale. If a product needs replacement to retain the original arrival position, it requires a different contract and separate handling of version identity.
- Pick a FIFO representation. Why can removing N items with repeated list
pop(0)take quadratic work? Would a bounded deque be safe for jobs that must all run?
Track movement and eviction
Answer: Front removal shifts approximately N−1, N−2, …, 0 references, whose sum is quadratic. A deque avoids those shifts. An unbounded deque is the appropriate FIFO starting point; a full bounded deque can evict pending work when appending, so its capacity policy must not be mistaken for harmless storage optimization.
- Check immutability. Can
([1,2],)serve as a dictionary key? What about('job',7)?
Inspect the contained values
Answer: The first tuple contains an unhashable list and cannot be a key, even though the tuple’s slot cannot be reassigned. The second contains a string and an integer and is hashable. A tuple does not recursively freeze the objects it references.
Interfaces make algorithmic costs visible
The MIT sequence-interface analysis compares arrays, linked lists and dynamic arrays by the operations they support. It is a useful habit: first write the required operations and invariants, then compare implementations under the expected workload. “A linked structure is faster” or “hashing is constant time” omits the operation and its conditions.
The Python tutorial, heap documentation and deque reference connect these abstractions to concrete language behavior. In AI work, the same choices appear in search frontiers, ID deduplication and the tables used by dynamic programming. Changing a container is safe only when it preserves the algorithm’s intended order, identity and update rules.
Make a prediction, then check
After ten puts for one ID and then cancellation, what does sizes return before cleanup?
Learning objectives
- Choose sequence, membership, mapping and ordering interfaces before choosing a container.
- Prove extraction correctness from heap order and current-version membership.
- Distinguish live records, stale heap entries, retained dictionary capacity and amortized costs.
Prerequisites & connections
Explore related knowledge →References
- Data Structures — Python 3.12 Tutorial
Python Software Foundation - heapq — Heap queue algorithm — Python 3.12
Python Software Foundation - collections — Container datatypes — Python 3.12
Python Software Foundation - 6.006 Introduction to Algorithms, Lecture 2: Data Structures
MIT OpenCourseWare · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Seven tests pass under actual CPython 3.12.12. An independent list-only scan queue checks 300 mixed operations and final draining; heap parent order, serial uniqueness and the bijection between active records and live heap entries hold after each operation. The oracle has no heap or stale-version mechanism.
- Checked update/cancel/reinsert, current-version tie order, compaction equivalence and idempotence, empty states, invalid-input preservation, 80-digit priorities, bounded-history eviction and tuple/hashability examples. Rebuilding costs include releasing the old heap and scanning/releasing retained dictionary capacity; heap comparisons are distinguished from list allocation amortization. Eight stdout lines reproduced.
- Complete original bilingual text, identical Python, three corresponding displays, six anchors and four answers pass strict MDX/KaTeX and actual React HTML/MathML. Only article_text controls test paths. Humanizer conventions followed; written records AI author checking, not human review. No service execution, concurrency guarantee, timing benchmark or whole-site build.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Data Structures — Python 3.12 Tutorial · Actually read §§5.1.1–5.1.2 stack/list-front shifts/deque, §5.3 tuple slots versus contained mutable objects, §5.4 sets, §5.5 dictionary replacement and insertion order. Article uses the more precise stable-hash/equality requirement, not an overbroad immutable-type claim.
- heapq — Heap queue algorithm — Python 3.12 · Actually read heap invariant, heappush/heappop, linear heapify and Priority Queue Implementation Notes (tie counters and removal/priority replacement). Our original implementation checks immutable (priority,serial) versions, uses None/bool API outcomes and compaction, rather than copying the documented mutable-entry/sentinel recipe. No third-party code assets copied.
- collections — Container datatypes — Python 3.12 · Actually read deque section, particularly lines 287–295: fast operations at both ends, O(n) list-front shifts and bounded-deque opposite-end eviction. No claim that the compound queue is a thread-safe transaction.
- 6.006 Introduction to Algorithms, Lecture 2: Data Structures · Actually read five-page official PDF: interface/representation distinction, sequence operation tables, dynamic-array reallocation and amortized analysis on pages 3–4, including explicit Python append/pop amortization and costly other operations. The geometric doubling derivation illustrates a model, not CPython’s exact growth factor.
- Data Structures — Python 3.12 Tutorial · Actually opened the official versioned tutorial, displayed 3.12.13. Read sections 5.1.1–5.1.2 on stack/queue shifts, 5.3 tuple slot versus nested mutability, 5.4 membership, and 5.5 key replacement/insertion order. The article correctly narrows broad tutorial language to stable hash consistent with equality.
- heapq — Heap queue algorithm — Python 3.12 · Actually read the official heap page, especially heap invariant/heapify and Priority Queue Implementation Notes lines 87–138: unique counters, ties, updates and removal. Confirmed that the article uses its own immutable version-matching design, not a claimed verbatim official recipe.
- collections — Container datatypes — Python 3.12 · Actually read deque lines 287–295 and methods through 385: end-operation costs, bounded opposite-end eviction, middle-index costs and the distinction between individual operations and compound transactions.
- 6.006 Introduction to Algorithms, Lecture 2: Data Structures · Actually opened the five-page Spring 2020 PDF and read printed pages 1–4: interfaces versus representation, sequence operations, dynamic-array allocation/deletion and amortized analysis. No visual scan review or transfer of a literal CPython growth factor claimed.
Related topics