Deque, Counter and defaultdict
Choose specialised containers for queues, counts and grouped records.
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: 14 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.
- Explain choose operations before containers
- Apply group records without shared defaults
- Reason about when not to specialise
Choose operations before containers
Choose a collection by the operations and information it must preserve. A specialised container is useful when it makes a repeated job clearer or avoids unnecessary work.
Understand first
A first-in-first-out queue, a frequency table and grouped records are different jobs. collections supplies deque, Counter and defaultdict so each job can have an explicit model.
Words you will see
- deque
- A double-ended queue with efficient additions and removals at either endpoint.
- Counter
- A dictionary-like collection of values and their counts.
- defaultdict
- A dictionary with a factory called by bracket lookup for an absent key.
Start with the workload, not the class name
A queue processes an earlier arrival before a later one. Repeated list.pop(0) shifts remaining entries, while deque.popleft removes from the front without that whole-list shift. A deque still has positions, but repeated middle indexing is not its strength. A list remains a good choice for direct indexed access and end appends.
A Counter records frequencies rather than every occurrence. A defaultdict can create a group when the first event arrives. Neither replaces a sequence when occurrence order itself is the required information. Explain what you would lose before changing the container.
Read the method's effect and result separately
append adds at the right and returns None. popleft removes and returns the leftmost item; it raises IndexError if the queue is empty. The example guards the second removal because an empty queue is an expected boundary case here.
Do not describe a Python deque as durable messaging. It lives in this process and does not provide acknowledgment, retry delivery or persistence. It is an in-memory data structure, not a substitute for a job service.
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(["Ada"])Start with one earlier arrival.
queue.append("Lin")Add a later arrival at the right.
print(queue.popleft())Remove and display Ada from the left.
print(bool(queue))After the second removal, the queue is empty and false in a condition.
A list is strong at indexed access and append/pop at the end. A deque supports efficient append/pop at either end; random indexing near its middle is not its purpose. Counter expresses frequencies. defaultdict expresses missing-key construction when creating a value is the intended write behaviour.
FIFO: arrival and removal are different endpoints
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- ArriveAda, then Lin enter from the right.
- RemoveAda leaves from the left.
- RemainLin waits; the earlier arrival rule is preserved.
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 an urgent item at the front.
Try: Use queue.appendleft("Sam") before the first removal.
Sam leaves first because you intentionally changed the queue policy.
Observe an empty removal.
Try: Add another queue.popleft() after both names have left.
Actual execution reports IndexError instead of a pretend job.
Before you move on
Which collection would you choose for frequent front removals, and what if every item instead needs repeated indexed access?
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
A deque fits frequent endpoint work; a list generally fits repeated random indexing. Container choice follows the operations, not a universal ranking.
Group records without shared defaults
A default factory should create a value only when a missing-key write is intended. Each group needs its own mutable list.
Understand first
Grouping API and worker events into separate lists is useful, but a shared default list can make unrelated groups change together. Read-only inspection should also not accidentally create a group.
Words you will see
- Factory
- A callable invoked to produce a value, such as list producing a fresh empty list.
- Bracket lookup
- A read using groups[key], which can trigger defaultdict's missing-key behavior.
- Bounded deque
- A deque with maxlen that discards from the opposite end when an append exceeds capacity.
Creating a group is observable mutation
defaultdict(list) stores the callable list, not one prebuilt list. The first groups["api"] access calls list to make an empty list and inserts it under api. The first worker access calls list again, making a different inner list.
groups.get("missing") does not invoke that factory. It returns None by default and leaves the mapping unchanged. Bracket access and get therefore have different meanings; choose the one matching whether this access should create state.
An automatic default is not always safe
Use an ordinary dictionary if an absent service name should reveal a bug. A convenient factory can hide spelling mistakes by inventing empty groups. For optional reads, membership or get may be the correct operation even when the object is a defaultdict.
A deque with maxlen can deliberately retain only a recent window, but appending to a full window drops old entries. This can be useful for history display and wrong for work that must never be lost. Capacity should be part of the stated contract, not an unexplained memory shortcut.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
print(groups.get("api"))Read a missing value without calling list or inserting api.
groups["api"].append(2)Create api's list on its first bracket access, then append.
groups["worker"].append(1)Create a different list for worker.
recent.append(3)The full two-entry history drops 1 and retains 2, 3.
A defaultdict(list) calls list separately for each absent key accessed with brackets. get does not invoke that factory. This distinction matters when a read must not change the mapping. A bounded deque can drop items automatically, so use maxlen only when discarding old entries is deliberate.
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.
Trigger the factory without appending.
Try: Replace groups.get("api") with groups["api"].
The membership print becomes True because bracket access inserted a list.
Increase the history capacity.
Try: Change maxlen=2 to maxlen=3.
Appending 3 retains [1, 2, 3] instead of discarding the oldest value.
Before you move on
Does groups.get('new') leave a new empty list in the mapping? Why does groups['new'] differ?
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
get is an optional read and does not invoke the factory. Bracket lookup invokes the factory for a missing key and inserts the fresh value, changing the mapping.
Process a queue and group events
A short pipeline can use different containers for different responsibilities: queue order, remaining frequencies and grouped measurements.
Understand first
One service event may need to leave a queue, update a summary and enter a service-specific group. Trace these steps separately so no collection's output is mistaken for another's state.
Words you will see
- FIFO
- First in, first out: the oldest queued entry is selected first.
- Group
- A key with all associated records kept together.
- Snapshot
- A representation of contents at a particular point; nested values may still be shared.
Follow the queue before computing its summary
The queue begins api, worker, then appends another api. popleft removes the first api. Only worker and the later api remain when Counter(queue) counts memberships. The removed event is not included in that remaining-queue summary.
Counter keeps the order of first encounters in this input, so converting it to a dictionary displays worker then api. This is insertion-order behavior, not a reason to depend on set ordering or sorted priority.
Group records without losing the values
The second loop reads pairs containing a service name and measurement. groups[name].append(value) creates the first list for each service, then keeps all that service's values in encounter order. Two api measurements remain [2, 3] rather than being added together.
dict(groups) makes an ordinary outer dictionary for display. It does not recursively clone the inner lists. A group can still grow with every retained event, so choosing a streaming input does not by itself bound output memory.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
queue.append('api')The queue now holds api, worker, api.
print(queue.popleft())Remove and display the first api.
print(dict(Counter(queue)))Count only the two remaining events.
groups[name].append(value)Preserve each service's measurement occurrences in its own list.
Remove the oldest queued event, then group independent lists per service. Mapping insertion order determines this display; no set ordering is assumed.
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.
Count before removing.
Try: Print dict(Counter(queue)) before popleft as well.
The earlier snapshot includes two api occurrences.
Give worker another measurement.
Try: Add ('worker', 4) to the pair list.
Worker's separate group becomes [1, 4]; api remains [2, 3].
Before you move on
Would groups for api be 5 or [2, 3]? How would you change the model if a total were required?
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
It is [2, 3] because the rule stores individual measurements. A total needs an explicit addition rule under each key, not list appends.
Where this idea earns its place
The collections module captures recurring data-structure intent. Counter means frequency, defaultdict means an explicit missing-value construction policy and deque means efficient endpoint operations. Using these types can make code clearer, but only when their semantics match the workflow rather than being selected because they appear more advanced.
Follow the mechanism step by step
A deque avoids shifting the entire remainder on endpoint removal. Counter updates count values by key. defaultdict calls its factory for missing bracket lookup and inserts the result, while get does not. That means a seemingly harmless read through brackets can mutate the mapping and change later iteration or size checks.
Work through a concrete application
For a service-event report, use a deque only while pending events need FIFO handling, then aggregate counts separately. For grouped records, construct independent lists via defaultdict(list) and convert to an ordinary dict if the published result should no longer create missing keys. Trace a missing get and a missing bracket access side by side.
Failure cases and misleading shortcuts
A bounded deque drops entries when appends exceed maxlen, which can be unacceptable for required work. Counter can hold zero or negative counts, so it is not automatically a validation mechanism. A defaultdict factory that returns one pre-existing mutable object recreates shared-state bugs despite using a specialised container.
Cost, ownership and alternatives
Specialisation does not remove resource limits. A queue needs bounded admission, and grouping every unique user can consume unbounded memory. Deque middle indexing is not its strongest operation. For durable jobs, use a system with persistence and acknowledgments; no in-process collection can recover accepted work after process loss by itself.
Verify the contract
Test each type's unusual boundary: missing-key access, zero counts, endpoint removal on empty input and bounded-deque eviction. Check the actual workload's ordering and data-loss requirements. When a collection is accessed across threads, protect the whole application invariant instead of assuming every multi-step sequence inherits atomicity from individual operations.
Transfer question: Why might defaultdict be inappropriate for a read-only configuration object?
Accessing an absent key with brackets can create an entry, masking a misspelling and changing state during a read. Use an ordinary mapping and a deliberate absence/error policy when keys must already exist.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Process a queue and group events
Without copying the worked code, reproduce its observable contract: Remove the oldest queued event, then group independent lists per service. Mapping insertion order determines this display; no set ordering is assumed. Then change one boundary input and explain the result.
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.
Guided: process arrivals in order
Return the dequeued order without consuming the caller's list.
The contract
- Input is a list of name strings.
- Return a new list of the names in first-in-first-out order, including duplicates.
- Do not mutate the input; empty input gives an independent empty result.
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
assert drain_fifo(["Ada", "Lin"]) == ["Ada", "Lin"], "Keep FIFO order"
- duplicates
assert drain_fifo(["x", "x", "y"]) == ["x", "x", "y"], "Keep every arrival"
- empty
assert drain_fifo([]) == [], "Empty queue produces an empty list"
- one item
assert drain_fifo(["x"]) == ["x"], "One item is processed once"
- source preserved
items = ["b", "a"] result = drain_fifo(items) assert isinstance(result, list) and result == ["b", "a"] and items == ["b", "a"] and result is not items, "Return an independent list without consuming input"
- independent empty calls
first = drain_fifo([]) second = drain_fifo([]) assert first == [] and second == [] and first is not second, "Each call returns its own empty list"
Why not repeatedly pop(0) from the caller's list?
That edits the caller and repeatedly shifts list entries. The deque copy preserves the input and processes n events in O(n) total work, with O(n) queue/result storage.
Guided: keep each service's measurements
Return independent grouped lists while preserving encounter order.
The contract
- Input is a list of (service string, integer value) pairs.
- Return an ordinary dict mapping each service to a list of its values in input order.
- Each service needs a separate list; preserve inputs and keep keys in first-service order.
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.
- group repeated service
assert group_events([("a", 2), ("a", 3), ("b", 1)]) == {"a": [2, 3], "b": [1]}, "Keep measurements, not totals" - empty
assert group_events([]) == {}, "Empty input creates no group" - duplicates
assert group_events([("a", 2), ("a", 2)]) == {"a": [2, 2]}, "Keep repeated records" - first service order
assert list(group_events([("b", 1), ("a", 2), ("b", 3)])) == ["b", "a"], "Keep first-service order" - source and type
events = [("a", 1)] result = group_events(events) assert type(result) is dict and result == {"a": [1]} and events == [("a", 1)], "Return a plain dict and preserve input" - separate groups
result = group_events([("a", 1), ("b", 2)]) assert result == {"a": [1], "b": [2]} and result["a"] is not result["b"], "Do not share group lists"
Does returning dict(groups) deeply copy the lists?
No. Here the function created each inner list for this result, so returning those lists is intended. Grouping n events into u services uses average O(n) work and O(n + u) retained result storage.
Transfer: retain only the last k arrivals
Change the queue requirement: this result is a bounded history, not every job waiting to be processed.
The contract
- Input is a list of strings and nonnegative integer capacity.
- Return the last capacity occurrences in original order as a fresh list.
- Capacity zero gives []; preserve the input and duplicates; this intentional dropping is not a durable work queue.
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.
- last two
assert recent_arrivals(["a", "b", "c"], 2) == ["b", "c"], "Keep newest occurrences"
- zero capacity
assert recent_arrivals(["a", "b"], 0) == [], "Zero capacity keeps nothing"
- larger capacity
assert recent_arrivals(["a"], 5) == ["a"], "Do not invent entries"
- duplicates
assert recent_arrivals(["a", "a", "b"], 2) == ["a", "b"], "Occurrences still matter"
- empty
assert recent_arrivals([], 3) == [], "An empty history stays empty"
- ownership
items = ["a", "b"] result = recent_arrivals(items, 3) assert isinstance(result, list) and result == ["a", "b"] and result is not items and items == ["a", "b"], "Keep an independent result"
Why is this not the same contract as drain_fifo?
This history deliberately discards old occurrences beyond capacity. For n arrivals and capacity k, construction is O(n) and retained storage O(min(n, k)); those data-loss semantics would be wrong for an unacknowledged job queue.
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 milestoneMemory and work
Efficient endpoint operations do not make a whole pipeline constant-time or memory-bounded. Count all stored records and all repeated operations.
Understand first
A queue or grouping service can use an appropriate container and still retain an unbounded history. Performance claims should identify the operation and retained data, not just the class name.
Words you will see
- n / u
- Here n is the event count and u is the number of distinct services.
- Average complexity
- Expected work under ordinary hashing and bounded-cost equality, not a worst-case promise.
- Retention
- Which records remain stored and for how long.
Count total work, not only one endpoint operation
Deque additions/removals at endpoints are approximately constant-time; list front removals need to shift later references. Neither observation makes processing n events free: reading each event still takes work. Middle access in a deque becomes slower with distance from an endpoint.
Counter and defaultdict use dictionary operations, so hashing and equality costs matter. Ordinary construction over n values is average O(n), but costly keys and collisions can change that behavior. Avoid a benchmark claim when no representative workload was measured.
A summary and full grouped history retain different amounts
A counter retains roughly one count per distinct key, O(u). Grouping all n events into inner lists retains O(n + u) outer entries and value references. Iterating a generator does not bound memory if the output still stores every event.
Choose whether to retain a rolling window, aggregate totals, flush groups to a durable store or keep all records. Each choice changes the product contract. A deque's maxlen implements intentional dropping, not backpressure or acknowledged delivery.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
counts[service] += 1Retain one numeric summary per service.
groups[service].append(value)Retain each individual measurement reference.
print(len(counts))There are two distinct service counts.
print(sum(len(values) for values in groups.values()))All three measurement occurrences remain stored.
Deque endpoint operations avoid shifting all remaining references. Counter and defaultdict inherit hash-table assumptions: expected constant-time lookups can degrade with costly equality or collisions. Each stored key/value and each grouped item consumes memory; grouping an entire stream is not automatically bounded.
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 repeated event.
Try: Append ("api", 9) to events.
The key count stays two while retained measurements become four.
Keep only counts.
Try: Remove the groups append and final grouped print.
The summary intentionally no longer preserves individual values.
Before you move on
If one service receives a million events, how do Counter and grouped lists differ in retained entries?
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
A counter can keep one accumulated count for that service; a grouped list still holds a million references if no retention policy removes them. Numeric size and object overhead also matter, but the growth models are different.
When not to specialise
A container solves an in-memory data-structure problem. It does not automatically supply validation, transactions, durability or multi-step concurrency safety.
Understand first
It is easy to stretch a convenient queue or default beyond its promise. Good engineering makes missing data and compound operations explicit.
Words you will see
- Durability
- State surviving a process or machine failure.
- Compound operation
- Several steps whose combined behavior may need synchronization.
- Missing-data policy
- Whether absence is valid, should create state, or should raise an error.
Choose ordinary tools when absence should be visible
A dictionary without a factory raises KeyError for a missing bracket lookup. This is useful when a miss means the program was given an invalid service identifier. A defaultdict would instead create a value, possibly hiding the mistake.
Counter reads of absent keys give zero, but that is a frequency semantics choice. It is not a suitable default for every business quantity. Zero inventory, unknown inventory and a nonexistent record can mean different things.
Separate individual operations from a larger protocol
A deque does not acknowledge that a job was processed or restore it after a crash. Checking if a queue is nonempty and then removing is two steps; another participant can change the state between them unless the larger protocol prevents it.
Use a lock or a suitable synchronized queue for a local multi-step concurrency contract, and an external durable system when persistence/delivery is required. The browser lab deliberately does not pretend to demonstrate cross-process or network delivery.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
print(counts["worker"])Counter reads zero without inserting worker.
print("worker" in counts)Membership remains False.
print(settings["worker"])An ordinary dictionary treats the missing service as an error.
print("unknown service")Report the specific expected absence rather than fabricating a setting.
Use an ordinary dict when an absent key should signal a mistake. Use a list for repeated random indexing. A deque is not a durable queue and does not provide acknowledgment or cross-process delivery guarantees. Concurrent multi-step operations need their own synchronization contract.
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.
Store the missing count explicitly.
Try: Add counts["worker"] = 0 before membership is printed.
Membership becomes True even though the count is still zero.
Use an optional dictionary read.
Try: Replace settings["worker"] with settings.get("worker").
It returns None without insertion; decide whether that is the intended policy.
Before you move on
Would serializing one deque operation guarantee an entire check-then-remove workflow is atomic?
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. Atomicity must cover the relevant sequence of steps, not just each step separately. A concurrent workflow needs an explicit synchronization or queue contract.
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.