Scenario: a queue becomes slower as it grows
A job consumer stores work in a list and repeatedly calls pop(0). Small tests look fast, but draining a much larger batch takes disproportionately longer even though processing each job is trivial.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Build a diagnosis from evidence
- Compare a repair with its trade-offs
- Test the changed behaviour
Follow the evidence.
A job consumer stores work in a list and repeatedly calls pop(0). Small tests look fast, but draining a much larger batch takes disproportionately longer even though processing each job is trivial.
Observed evidence
- Profiles show substantial time in front removal.
- The queue is used only at its endpoints.
- The consumer does not need random access to middle positions.
Investigation sequence
- Measure several input sizes and isolate queue operations from job work.
- Count reference shifts required by repeated list front removals.
- Replace the queue structure and verify ordering before comparing performance.
Challenge the repair
- Add a test for an empty queue and repeated values without changing FIFO order.
- Which metrics would distinguish a slow queue from a slow downstream database?
Read the incident, not just the error
A growing queue is evidence of a backlog, not proof that its container is slow. Separate removing a job from doing the job before choosing a repair.
Understand first
A worker can fall behind because removal moves many references, because a database is slow, or because arrivals exceed capacity. These causes need different changes.
Words you will see
- Backlog
- Accepted work that has not yet been handled.
- Hypothesis
- A possible cause with a prediction that evidence could contradict.
- FIFO
- First in, first out: consume jobs in their arrival order.
Reduce the incident without changing its order
The reported consumer removes position zero from a list. Reproduce that operation with three named jobs and no database, clock or network. The output shows arrival order, including duplicates. It does not show that the small program was slow, nor measure a production speedup.
Hypothesise that shifting remaining list entries dominates removal. A profile placing most time in job processing would weaken that hypothesis. Keep removal, waiting and processing as separate stages in a real investigation. Queue depth alone cannot distinguish them.
Name the ownership boundary
This fixture owns its jobs list and deliberately drains it. The loop condition checks whether any jobs remain before pop(0), so an empty queue is safe. A helper borrowing a caller's list might instead promise to preserve it; that would be a different API.
Iterating the list without removing items also preserves FIFO for a fixed batch. Use that simpler alternative when there are no new arrivals and no need to observe pending work. A live queue requires a clearer contract for arrivals, removal and capacity.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
jobs = ['a', 'b', 'a']Use three entries, not a set: both a jobs matter.
while jobs:Stop before attempting a removal from an empty list.
processed.append(jobs.pop(0))Remove the oldest entry and record it; the remaining entries shift.
print(jobs)Confirm the locally owned queue was drained.
A job consumer stores work in a list and repeatedly calls pop(0). Small tests look fast, but draining a much larger batch takes disproportionately longer even though processing each job is trivial.
Conceptual cause chain, not a measured performance trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Arriven jobs occupy ordered list entries.
- Removepop(0) returns the oldest job and shifts the remaining references.
- RepeatRepeated front shifts add work as the initial backlog grows.
- Repairdeque.popleft keeps FIFO without shifting all remaining entries.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Make the order violation visible.
Try: Replace pop(0) with pop() and use ['a', 'b', 'c'].
The result becomes c, b, a: faster endpoint access is not a correct FIFO repair.
Try the empty boundary.
Try: Start jobs as [].
Both printed lists are empty; the loop never attempts a removal.
Before you move on
If removal becomes negligible but job age keeps rising, has the queue repair failed to preserve FIFO?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Not necessarily. FIFO is an order rule, not a throughput guarantee. Check arrival rate, processing rate and downstream waiting before choosing another repair.
Investigate before changing code
Count the work an operation requires before interpreting a timing result. Repeated front removal hides changing work inside a simple-looking loop.
Understand first
A tiny deterministic work model explains why draining larger lists can scale poorly without making machine-specific timing claims.
Words you will see
- Reference
- A connection from a container entry to a Python object; shifting it does not copy the job itself.
- Quadratic
- Work growing roughly with the square of the item count.
- Model
- A simplified explanation of a mechanism, not a measurement of a running interpreter.
Add the remaining lengths
For four entries, the first removal moves three remaining references, then two, then one, then zero. The sum is six. The program computes this arithmetic only; it is not instrumenting the interpreter or measuring CPU instructions.
For n entries, this model totals n times (n minus one) divided by two reference shifts. Doubling a large n therefore approaches four times this part of the work. Real elapsed time also contains allocation, job work and scheduling, so do not equate the model with a stopwatch.
Use measurements to test relevance
In a real local lab, compare multiple input sizes using identical trivial jobs, and then repeat representative end-to-end workloads. Keep the environment and measurement boundary explicit. A database-dominated incident might show almost no useful change after switching containers.
A deque avoids the shifting mechanism, while an index walking a fixed list also avoids deletion. The index approach keeps consumed references alive until the list is released or compacted. Choose according to whether retaining completed jobs violates the ownership and storage contract.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
for size in [0, 1, 4, 8]:Choose input sizes, including empty and singleton boundaries.
shifts = sum(range(size))Add 0 through size minus one: the lengths left after each removal.
print(size, shifts)Display the model count, not measured duration or memory.
Measure several input sizes and isolate queue operations from job work. Count reference shifts required by repeated list front removals. Replace the queue structure and verify ordering before comparing performance.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Add a larger model case.
Try: Include 16 in the size list.
It prints 16 120; no real queue or timer was used.
Test the next boundary.
Try: Include 2.
It prints 2 1 because only the first front removal shifts another entry.
Before you move on
A fixed batch can be read once without deleting anything. Must it be converted to a deque?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. A for loop over the existing batch is linear traversal and preserves it. A deque is useful when pending work really needs endpoint insertion and removal.
A repair you can explain
A deque is a double-ended queue. Use append for arrival and popleft for FIFO removal when work is local and only endpoint access is needed.
Understand first
Changing the representation can remove unnecessary shifting while leaving job order and duplicate handling unchanged.
Words you will see
- deque
- The standard-library container designed for efficient operations at either end.
- Endpoint
- The front or back of a sequence.
- Delivery guarantee
- A promise about surviving failures and handling accepted work, not just container order.
Explain the existing repair
The import provides deque from collections. The constructor places a, b and c in that order. popleft removes a first, then b, then c; append records each removed job in processed. The while condition prevents an empty removal.
This locally created queue belongs to the sample, so draining it is intentional. A borrowed deque should be documented as consumed. A deque does not deep-copy job objects: mutating a returned job can still affect another owner holding the same job.
Keep the promise narrow
For n jobs the drain performs n endpoint removals and n result appends, rather than the list's quadratic front-shift pattern. The output list still retains n job references. If results need not be retained, process each job without accumulating a report.
A deque is not a durable broker, a completion acknowledgement, or an entire concurrent worker protocol. Middle indexing is not its strength. A fixed batch may need only iteration; threaded coordination may need queue.Queue; crash recovery needs persistent handoff outside this browser-local example.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
queue = deque(['a', 'b', 'c'])Build the same arrival order in a different container.
while queue:Only remove when the locally owned deque has an entry.
processed.append(queue.popleft())Take the oldest job, without shifting every remaining list entry.
print(processed)Verify order; this is not a timing benchmark.
The deque preserves FIFO order while avoiding a shift of every remaining list reference for each consumed item. The example verifies ordering rather than asserting machine-specific timing.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Retain repeated jobs.
Try: Change the initial input to ['a', 'a', 'c'].
Both a entries remain and are processed before c.
Observe local consumption.
Try: Add print(list(queue)) after the loop.
It prints [] because this repair consumes its queue.
Before you move on
If two entries refer to the same mutable job dictionary, will converting to deque isolate them?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The deque stores references to the original jobs. It changes endpoint behavior, not nested ownership or the job objects' identities.
Reproduce growth while isolating the consumer
Use a batch of trivial jobs and measure draining several input sizes while excluding real job execution. The incident predicts disproportionately larger cost as the list grows because the consumer repeatedly removes position zero. Preserve FIFO ordering as the behavioral contract while investigating speed. A profile that shows most time in a downstream database would contradict the queue hypothesis, so collect stage-level evidence rather than replacing a container solely because the whole job is slow.
Compare enqueue time, time waiting for a job, removal work, and job processing. Record queue depth and completed-job rate together. A long queue can be a symptom of slow downstream work rather than an inefficient removal operation. Keep the fixture's work intentionally cheap to expose reference movement, then repeat representative end-to-end measurements after repair. Do not assert exact timing in a regression test because machine load and interpreter differences make that brittle.
Count the hidden reference shifts
A list stores a sequence of object references with efficient indexing. Removing its first item shifts the remaining references toward the front. For n pending jobs, successive front removals move roughly n minus one, n minus two, and so on references. Their sum grows quadratically, even though each actual job does almost nothing. A while loop that looks linear in the number of iterations therefore contains an operation whose cost changes with remaining size.
The given queue uses only endpoint operations and does not require middle indexing. A deque fits that contract: append accepts work at one end and popleft removes the oldest item without shifting every remaining list entry. Draining n items now requires O(n) endpoint operations under the usual container model. The job objects still consume their own memory, so replacing the container does not make an arbitrarily large backlog inexpensive to retain.
Repair the structure without changing delivery semantics
The reference deque consumes a, b, and c in that order. Keep that observable result while changing the representation. If other code indexes or slices the middle of the queue, audit those consumers rather than assuming a deque is a drop-in replacement for every list operation. If only a one-time list traversal is needed, iterating the list without removing items may be simpler and avoids front-removal work without introducing queue behavior at all.
Define capacity and overload behavior independently from endpoint efficiency. A bounded deque that silently discards entries when full is not appropriate for jobs that must not disappear. A producer/consumer queue may need waiting or explicit rejection instead. Local memory structures provide neither durable acknowledgment nor recovery after process loss. If those are requirements, choose a durable handoff and a replay policy; a faster local deque cannot establish delivery guarantees across crashes.
Verify order and distinguish remaining bottlenecks
Test an empty queue, one job, repeated values, and interleaved arrivals and removals. Use identifiers as well as values if duplicate jobs must remain distinguishable. Confirm that accepted jobs appear in FIFO order and that no result disappears. For performance evidence, compare increasing batch sizes using the same trivial processing function and report the workload and runtime environment, not a universal speed multiplier derived from one successful small run.
If throughput remains low after removal cost is fixed, examine worker utilization, downstream latency, retry rate, and queue age. A fast container can make backlog growth more visible without solving an overloaded consumer. Bound the backlog and choose whether producers wait, fail, or persist elsewhere. Test that policy under a full queue with coordinated producer and consumer actions, and verify shutdown behavior for accepted jobs rather than treating an empty local container as proof of completed external work.
Transfer question: After switching to deque, queue depth still rises while removal time is negligible. How do you decide the next change?
Measure arrival rate against completed-job rate and break job time into downstream waiting and local computation. If the database dominates, increasing producers or optimizing deque operations adds pressure without capacity. Evaluate a bounded worker count against database capacity, enforce backlog limits, and choose a documented overload response. Track oldest-job age as well as depth because bursts and sustained overload differ. Verify any change with the same representative workload and ordering tests. If jobs must survive restart, add durable handoff and acknowledgment semantics instead of claiming that the deque repair solved reliability.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Recreate the repair independently
Add a test for an empty queue and repeated values without changing FIFO order. Start from the symptoms and write your own regression assertion before opening the reference.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Read a fixed FIFO batch without taking ownership
Return an ordered shallow list copy of a caller's fixed job list. This batch needs no queue mutation.
The contract
- Input is a finite list of arbitrary job objects; return a new built-in list in the same order, retaining duplicates.
- Do not mutate the input or clone its job objects: each result entry must be the same object as its input entry.
- Empty input returns a new empty list. No I/O, timing, threads or persistent-delivery promise is involved.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Arrival order
jobs = ['b', 'a', 'c'] result = fifo_copy(jobs) assert type(result) is list and result == ['b', 'a', 'c'] and result is not jobs and jobs == ['b', 'a', 'c']
- Fresh empty result
jobs = [] result = fifo_copy(jobs) assert type(result) is list and result == [] and result is not jobs and jobs == []
- Repeated identities
job = {} jobs = [job, job] result = fifo_copy(jobs) assert type(result) is list and len(result) == 2 and result is not jobs and result[0] is job and result[1] is job and len(jobs) == 2 and jobs[0] is job and jobs[1] is job - Nested sharing
job = {'steps': []} jobs = [job] result = fifo_copy(jobs) assert type(result) is list and result is not jobs and result == jobs and result[0] is job result[0]['steps'].append('run') assert jobs == [{'steps': ['run']}] - Result append isolation
jobs = [1] result = fifo_copy(jobs) assert type(result) is list and result == [1] and result is not jobs result.append(2) assert jobs == [1]
- Caller append isolation
jobs = [None, 0] result = fifo_copy(jobs) assert type(result) is list and result == [None, 0] and result is not jobs jobs.append(False) assert result == [None, 0] and jobs == [None, 0, False]
Why not repeatedly pop(0) from a copy?
It would preserve the caller but introduce avoidable quadratic reference shifts. A shallow list copy takes linear traversal and n result references, while sharing the original job objects.
Take at most a requested number of pending jobs
Borrow a deque and deliberately remove only its oldest requested jobs.
The contract
- Input is a collections.deque of arbitrary jobs and an integer limit. Return a built-in list of at most limit oldest entries, preserving order and duplicates.
- Consume those entries from the caller's deque; leave remaining entries and all job identities unchanged. Do not modify the deque's maxlen.
- Zero consumes nothing. Negative limit raises ValueError before touching the deque; if fewer jobs exist, return them all.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Prefix and remainder
from collections import deque q = deque(['a', 'b', 'c']) r = take_jobs(q, 2) assert type(r) is list and r == ['a', 'b'] and list(q) == ['c']
- Empty queue
from collections import deque q = deque() r = take_jobs(q, 3) assert type(r) is list and r == [] and list(q) == []
- Zero leaves identities
from collections import deque a = object() q = deque([a], maxlen=3) r = take_jobs(q, 0) assert type(r) is list and r == [] and len(q) == 1 and q[0] is a and q.maxlen == 3
- Oversized request
from collections import deque a = object() q = deque([a]) r = take_jobs(q, 9) assert type(r) is list and len(r) == 1 and r[0] is a and not q
- Duplicate and remaining identity
from collections import deque a, b = {}, {} q = deque([a, a, b]) r = take_jobs(q, 2) assert type(r) is list and len(r) == 2 and r[0] is a and r[1] is a and len(q) == 1 and q[0] is b - Invalid limit preserves queue
from collections import deque a = object() q = deque([a]) try: take_jobs(q, -1) except ValueError: assert len(q) == 1 and q[0] is a else: raise AssertionError('negative limit accepted')
Does returning a job prove it finished?
No. The helper transfers references out of pending; processing is another boundary. Taking k jobs takes O(k) endpoint operations and k output references, where k is min(limit, queue length).
Transfer: reject overflow without losing accepted work
The requirement changes from draining efficiently to admitting safely. Return an explicit boolean and never evict a pending job.
The contract
- Input is an unbounded deque (maxlen is None), an arbitrary job and an integer capacity. Return True only if appending at the right succeeds under the count limit.
- When len(pending) >= capacity return False with the deque unchanged, including order and identity. Capacity zero rejects even into an empty deque.
- Negative capacity raises ValueError before mutation. Accepted jobs are the same objects, not copies. This single-threaded check is not a concurrency or byte-memory bound.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Accept at back
from collections import deque a, b = object(), object() q = deque([a]) r = offer_job(q, b, 2) assert type(r) is bool and r is True and len(q) == 2 and q[0] is a and q[1] is b and q.maxlen is None
- Reject full queue
from collections import deque a, b = object(), object() q = deque([a]) r = offer_job(q, b, 1) assert type(r) is bool and r is False and len(q) == 1 and q[0] is a
- Zero capacity
from collections import deque q = deque() r = offer_job(q, 'a', 0) assert type(r) is bool and r is False and list(q) == []
- Repeated same object
from collections import deque a = {} q = deque([a]) r = offer_job(q, a, 3) assert type(r) is bool and r is True and len(q) == 2 and q[0] is a and q[1] is a - Already over capacity
from collections import deque a, b = object(), object() q = deque([a, b]) r = offer_job(q, object(), 1) assert type(r) is bool and r is False and len(q) == 2 and q[0] is a and q[1] is b
- Negative validation
from collections import deque a = object() q = deque([a]) try: offer_job(q, object(), -1) except ValueError: assert len(q) == 1 and q[0] is a else: raise AssertionError('negative capacity accepted')
Why is deque(maxlen=capacity) not equivalent?
It can evict older accepted work on append instead of rejecting the new job. This helper uses constant endpoint operations but retains the existing backlog; concurrent admission needs separate coordination.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneThe underlying mechanism
A capacity rule is separate from fast removal. A bounded deque can silently discard old work, which may violate a job acceptance promise.
Understand first
A performance repair must not introduce data loss while trying to cap backlog storage.
Words you will see
- Capacity
- The maximum number of pending entries allowed by a policy.
- Eviction
- Automatically removing an existing entry to make room.
- Backpressure
- Making a producer wait or slow down when consumers cannot keep up.
Make silent eviction observable
deque with maxlen=2 retains at most two entries. Appending c to a and b discards a. This is appropriate for a recent-history display, but not for jobs that were accepted with a promise to run later. The program prints pending work, not completed work.
A growing backlog also means retained job objects can grow. Efficient endpoints do not make those objects free. State capacity in entries here; entries can have different sizes, so a count limit is not a measured byte limit.
Choose and test overload behavior
Alternatives include rejecting the new item without changing existing jobs, waiting for space, or persisting work elsewhere. Each moves a cost: rejection needs caller handling, waiting ties up producer time, and persistence adds operational complexity.
For a single-threaded helper, check capacity before append and return an explicit acceptance result. That check-and-append pair is not an atomic multi-producer protocol. Concurrent workers require coordination, and durable delivery requires more than an in-memory object.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
pending = deque(['a', 'b'], maxlen=2)Store two jobs at the configured retention limit.
pending.append('c')Accept c by evicting the oldest entry a.
print(list(pending))Reveal the lost pending job; no worker processed it.
One pop(0) on a list is O(n); draining n items can sum to O(n squared) reference movement. Deque endpoint operations avoid that pattern. Neither structure provides durable delivery or completion acknowledgment after a crash.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Compare unbounded behavior.
Try: Remove maxlen=2.
All three jobs remain; storage is no longer capped by this container.
Test zero retention explicitly.
Try: Use maxlen=0.
No entries are retained, even after append; this is not a useful pending-work queue.
Before you move on
For an audit log showing only the latest two observations, is this eviction necessarily a bug?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. A sliding recent-history window deliberately forgets older observations. The same mechanism is wrong only when the contract promises to preserve pending jobs.
Alternatives and operational trade-offs
A queue repair should survive interleaved arrivals and removals, not only a one-time drain. Test the order at the endpoint boundary.
Understand first
A batch-only test may miss a repair that puts new jobs ahead of work already waiting.
Words you will see
- Interleaving
- A sequence that alternates different operations, such as arrival and removal.
- Invariant
- A rule that must remain true after every permitted operation.
- Shallow ownership
- Owning the container while still sharing its contained job objects.
Follow the oldest remaining entry
Start with a and b. Removing a leaves b as the oldest pending job. Appending c places it behind b, so the next removal must be b, not c. The final pending list contains c. This is evidence for FIFO under this particular operation sequence.
A tempting appendleft repair would put c ahead of b. A pop-from-right repair would also violate the rule. Include repeated values and use object identity when equal-looking jobs must remain distinct.
Separate removal from success
The helper that takes jobs owns the act of removal but not necessarily the job object's mutable contents. If processing later raises, the removed job is no longer pending. Decide explicitly whether retries requeue it, and whether that changes order.
An alternative is traversing a stable batch without removal, but it does not represent live pending state. Another is a coordinated worker queue, which adds blocking and acknowledgement methods. Neither option automatically provides crash survival; this example demonstrates local order only.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
pending = deque(['a', 'b'])a was accepted before b.
print(pending.popleft())The first call removes a; the second removes b, which remains older than c.
pending.append('c')Place the new arrival after b.
print(list(pending))Only the new arrival remains pending.
A deque is suitable for local endpoint operations; a durable broker may be needed for cross-process delivery and recovery. A bounded queue also needs an explicit policy for waiting, rejection or dropping work.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Expose a priority change.
Try: Replace append('c') with appendleft('c').
The second print becomes c, demonstrating that this is no longer ordinary FIFO.
Inspect sharing without copying jobs.
Try: Use a dictionary as the first job and compare popleft() is that dictionary.
It is True: endpoint removal transfers the reference, not a deep copy.
Before you move on
If processing a fails after popleft, is a still in pending for an automatic retry?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Removal already changed pending. A retry policy must deliberately retain or requeue failed work, and consider duplicates and ordering.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.