Processes and CPU-bound work
Choose parallelism while accounting for serialization and startup.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
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.
Host subprocesses and multiprocessing require the local lab. Browser Python is not a process-capable operating system.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain use processes for appropriate cpu workloads
- Apply design a serializable task
- Reason about transfer and failure boundaries
Use processes for appropriate CPU workloads
A process is an operating-system execution container with its own ordinary memory. Separate processes can compute in parallel, but copying work and starting workers can cost more than the calculation.
Understand first
A CPU-heavy batch can be divided among cores when each part has enough useful work. First understand values, lists and functions. This copy model explains why changing a worker's ordinary list does not update a parent's list by magic.
Words you will see
- Process
- An OS-managed running program with its own ordinary address space.
- Serialization
- Encoding values so they can be transferred and reconstructed.
- Parallelism
- Actually executing work at the same time, for example on different CPU cores.
Separate memory changes the contract
json.dumps encodes the small parent record as text. json.loads builds a new dictionary and list. Appending eight changes the worker-owned list only. The output shows the unchanged parent and the expanded worker input before squaring it.
A real process pool commonly uses pickle-based transfer, not this JSON demonstration. Ordinary Python globals are not a shared result channel. Special shared-memory APIs exist but bring explicit ownership and synchronization duties; do not assume a copied list is shared memory.
Pay for the boundary deliberately
Use processes for sufficiently large, independent CPU tasks when that fits the runtime. Compare against a sequential baseline. Tiny tasks, large payloads and few jobs may spend most of their time starting workers and transferring data. Threads or async may be better for waiting-heavy I/O.
Browser Python is not a portable process-launch environment. The model runs there without OS privileges; a real lab needs supported local CPython, a saved importable .py file and OS process support. Empty input should return an empty result without inventing useful work or claiming a speedup.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
wire = json.dumps(parent)Encode the bounded parent values.
worker = json.loads(wire)Create an independent object graph for this JSON-shaped payload.
worker['values'].append(8)Change only the reconstructed list.
print(parent['values'])Observe that the original list still has two values.
Separate processes can run Python work on separate cores without sharing one conventional CPython GIL. They have separate memory, so inputs/results normally cross a serialization boundary. For tiny tasks, startup and transfer overhead may exceed the useful work.
Conceptual process boundary, not a running pool
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- ParentPrepare bounded plain values.
- TransferEncode and copy arguments to a worker's separate memory.
- WorkerCompute and return a result; the parent combines results.
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.
Change the worker's first value.
Try: Insert worker['values'][0] = 9 before printing.
The parent still prints [2, 5]; the worker prints [9, 5, 8].
Try empty payload work.
Try: Set parent = {'values': []}.
The parent remains empty; this program still deliberately adds eight to the worker before squaring.
Before you move on
If the reconstructed worker changes its first value to 99, what changes in the original parent list?
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
Nothing in this JSON-shaped fixture. The reconstructed list has separate ownership. Explicit result transfer is needed to bring changes back.
Design a serializable task
A process-friendly task has a clear input and result, and can be found when a child imports the script. Keep workers at module top level and put pool startup behind the main guard.
Understand first
Workers may finish in a different order from submission. Recording a job index lets a parent restore input order without confusing repeated values. This fixture requires tuples, enumerate and a top-level function; no real process API is needed to test that contract.
Words you will see
- Importable worker
- A function a child interpreter can find by importing a module.
- Main guard
- The if __name__ == '__main__' block that runs for direct script execution, not normal import.
- Job index
- A stable position used to associate one result with one submitted job.
Keep work separate from startup
square_job is defined at top level. It unpacks an index and value and returns the same index with the square. The main guard builds three jobs. reversed(jobs) intentionally makes the serial fixture return index two first, so ordering policy can be tested without timing.
Sorting indexed results restores positions zero, one and two. The two values of three stay two jobs rather than being collapsed into a dictionary keyed by input value. In a real boundary, also verify unique indices and complete coverage before publishing the result.
Know the startup boundary
A saved local script with top-level workers and a main guard is more portable than a nested closure submitted from an interactive cell. Process start-method defaults vary across Python versions and platforms. Do not assume a child inherits live connections or a safely initialized application.
ProcessPoolExecutor.map returns results in input order; an as_completed workflow needs its own mapping to inputs. This fixture models the latter ordering problem without claiming concurrency. For simple jobs and small lists, the serial comprehension may be the appropriate final implementation.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
index, value = jobSeparate identity from the value being squared.
return index, value * valueReturn enough information for later ordering.
returned = [square_job(job) for job in reversed(jobs)]Force a different return order deterministically.
ordered = [value for index, value in sorted(returned)]Restore the original input order using unique indices.
Keep worker functions importable at module top level and protect script startup with the main guard. Start-method defaults vary across versions/platforms. Do not assume a child inherits live connections, locks or a safely initialized web application.
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 negative value.
Try: Use [3, -2, 3] as input.
The ordered result becomes [9, 4, 9]; order follows indices, not square magnitude.
Remove the reversal.
Try: Replace reversed(jobs) with jobs.
returned changes order, but ordered stays [9, 1, 9].
Before you move on
For jobs made from [4, 4], may a result collector return one 16 because values are equal?
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 two input positions are two jobs. Preserve both results unless the contract explicitly requests deduplication.
Define a process-friendly pure task
A pure worker can be tested without starting processes. Pure means its result depends on its arguments and it does not change external state; this makes the calculation easier to validate separately from pool startup.
Understand first
Keep the original square fixture as the simplest trusted calculation. It needs only functions, multiplication and a list comprehension. A wrong square result is a worker bug; a serialization error is a different boundary failure and should not be hidden behind reference output.
Words you will see
- Pure function
- A calculation with no externally visible state changes and a result determined by its inputs.
- Serial baseline
- The same work performed without parallel workers for comparison.
- Pool lifecycle
- Starting, using and shutting down the owned worker processes.
Read the fixture without imagining workers
square returns one multiplied value. The main block builds three integers and calls square once for each, in input order. print shows a newly built result list. There is no import of a process API and no worker process to inspect.
For an actual local lab, save this complete program in square_lab.py. Under its main guard, import ProcessPoolExecutor, create it with max_workers=2 in a with block and print(list(pool.map(square, values))). Run the saved file using supported local CPython 3.11+ with OS process support, not a restricted browser.
Compare the right evidence
The serial and pool results should agree, including duplicates and negative numbers. The with block owns pool shutdown; consume results to observe exceptions. Do not treat a partially collected list after a worker crash as a valid complete answer.
Only benchmark after correctness, with bounded larger batches and measured startup/transfer costs. Three squares are intentionally too small to justify a speedup claim. Empty values yields []; using a process pool for that case adds startup without useful work. The lab remains separate from browser checks.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def square(value):Define the importable calculation once.
return value * valueCompute without touching outside state.
if __name__ == '__main__':Run the fixture only when invoked directly.
print([square(value) for value in values])Call sequentially and display three results.
This deterministic fixture tests the worker function, not a claim that a process pool was launched. Run the separate process lab below on your own supported environment.
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.
Test signed input.
Try: Set values = [-2, 0, 4].
The serial output becomes [4, 0, 16].
Test absent work.
Try: Set values = [].
The output is [] and square is never called.
Before you move on
What should the serial baseline return for [-3, 0, -3], and why keep both negative 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
It returns [9, 0, 9]. Each input position is a separate calculation; purity does not mean deduplicating equal inputs.
Where this idea earns its place
Process-based parallelism can suit substantial CPU work that does not scale through threads on the chosen interpreter. Each process has separate memory and lifecycle. That isolation changes the programming model: inputs and results must cross a transfer boundary, and failures can include worker exit or serialization errors rather than only ordinary function exceptions.
Follow the mechanism step by step
A process pool schedules importable worker functions with serializable arguments. Child initialization depends on the platform and selected start method. A main guard prevents recursive startup in relevant launch modes. Parent objects such as live sockets, locks or web application contexts should not be assumed safe or meaningful in the child.
Work through a concrete application
First test a pure square or parsing function in-process. Then save it in a real module, launch a bounded pool under the main guard and compare results with the serial reference. Increase workload size deliberately to find when useful computation outweighs startup and transfer. Label this as a separate OS-process lab, not a result established by a serial fixture.
Failure cases and misleading shortcuts
A function defined in a temporary interactive scope may not be importable by a spawned child. Returning a huge object can erase the benefit of parallel execution. A child crash is not a valid partial success, and retrying a task with side effects can duplicate those effects. Untrusted pickle payloads must never become an accepted input format.
Cost, ownership and alternatives
Account for one interpreter and memory footprint per worker, serialized copies, queued tasks and result buffering. Chunking reduces scheduling overhead but changes load balancing and cancellation granularity. Choosing a process pool for tiny functions can be slower than a direct loop even when multiple cores are available.
Verify the contract
Test the actual supported start method and packaged launch path. Include serialization failure, worker failure, empty work, ordering requirements and shutdown. Keep a deterministic unit suite for pure worker logic and a separately bounded integration suite for real process creation, so a green unit test is not mistaken for platform compatibility.
Transfer question: Why should a process worker avoid receiving a live database connection?
The connection's socket, transaction state and driver ownership belong to a particular process/runtime context. Pass a bounded task description and initialize an appropriately scoped connection in the worker if the architecture permits it. Also review whether database work is I/O-bound and better handled without processes.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Define a process-friendly pure task
Without copying the worked code, reproduce its observable contract: This deterministic fixture tests the worker function, not a claim that a process pool was launched. Run the separate process lab below on your own supported environment. 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: prepare bounded process payloads
Implement batch_items(values, size), keeping consecutive input positions in fresh batches and preserving an incomplete tail.
The contract
- values is a finite list of exact integers; repeats and negatives are valid. size is an exact integer. Raise ValueError when size <= 0, even for empty values.
- Return an exact list of fresh exact lists of at most size items. Flattening the result must equal values in its original order, including duplicates.
- Empty values with valid size returns []. Do not mutate values. Each batch is independently owned; integer elements need no deep copy.
- This tests payload grouping, not process startup, serialization or speed. Real process labs need a local OS and importable worker functions.
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.
- short tail is retained
out = batch_items([2, 3, 4, 5, 6], 2) assert type(out) is list and out == [[2, 3], [4, 5], [6]] and all(type(batch) is list for batch in out)
- empty is a fresh outer list
a = batch_items([], 3) b = batch_items([], 3) assert type(a) is list and a == [] and b == [] and a is not b
- large size still copies
values = [1, 2] out = batch_items(values, 9) assert type(out) is list and out == [[1, 2]] and out[0] is not values out[0].append(3) assert values == [1, 2]
- repeats signs and singleton size
out = batch_items([-1, -1, 0], 1) assert type(out) is list and out == [[-1], [-1], [0]] and out[0] is not out[1] and all(type(batch) is list for batch in out)
- invalid sizes fail even for empty input
for size in [0, -2]: raised = False try: batch_items([], size) except ValueError: raised = True assert raised - source and sibling ownership
values = [1, 2, 3, 4] out = batch_items(values, 2) assert type(out) is list and out == [[1, 2], [3, 4]] and values == [1, 2, 3, 4] and out[0] is not out[1] out[0][0] = 9 assert values == [1, 2, 3, 4] and out[1] == [3, 4]
Why is one giant batch not always the best process policy?
It can reduce transfer overhead but lose load balance and increase per-job memory. This copier takes O(n) element-copy time and O(n) result space for n values, plus batch-list overhead. It provides no process performance evidence.
Guided: verify complete indexed results
Implement ordered_results(records, count), accepting out-of-order arrival but rejecting duplicate, missing or unexpected job identities.
The contract
- count is a nonnegative exact integer. records is a finite list of (index, value) tuples with exact integer fields. Other shapes/types are outside the domain.
- Require exactly one record for each index in range(count). Raise ValueError on duplicate, missing, negative or out-of-range indices, even if duplicate values agree.
- Return a fresh exact list of values in index order. Repeated values are separate results; records stays unchanged. ordered_results([], 0) returns [].
- This is deterministic collection policy. It neither creates child processes nor validates real worker health or untrusted pickle input.
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.
- restore input positions
out = ordered_results([(2, 9), (0, 4), (1, 1)], 3) assert type(out) is list and out == [4, 1, 9] and all(type(value) is int for value in out)
- zero jobs own an empty list
a = ordered_results([], 0) b = ordered_results([], 0) assert type(a) is list and a == [] and b == [] and a is not b
- duplicate identity rejects even equal values
raised = False try: ordered_results([(0, 7), (0, 7)], 2) except ValueError: raised = True assert raised - missing identity rejects
raised = False try: ordered_results([(0, 7)], 2) except ValueError: raised = True assert raised - unexpected identities reject
for records, count in [([(-1, 4)], 1), ([(0, 4), (2, 9)], 2), ([(0, 4)], 0)]: raised = False try: ordered_results(records, count) except ValueError: raised = True assert raised - repeated values preserve records and ownership
records = [(1, 5), (0, 5)] out = ordered_results(records, 2) assert type(out) is list and out == [5, 5] and records == [(1, 5), (0, 5)] and out is not records out.append(8) assert records == [(1, 5), (0, 5)] and ordered_results(records, 2) == [5, 5]
Why is comparing only record count insufficient?
A duplicate can coexist with a missing index. Unique in-range identities plus full count establish coverage here. With n records and c required jobs the collector uses O(n + c) expected time and O(c) space, under ordinary dict assumptions; it does not prove process reliability.
Transfer: decide whether modeled parallel work pays
Implement should_parallelize(jobs, work, startup, transfer, workers). The new requirement includes startup and per-wave transfer cost rather than assuming more workers is better.
The contract
- All inputs are exact integers: jobs, work, startup and transfer are nonnegative; workers must be positive. Raise ValueError for workers <= 0, including zero jobs.
- Serial estimated cost is jobs * work. Parallel estimated cost is startup + ceil(jobs / workers) * (work + transfer). All costs use the same abstract units; transfer is the cost per wave in this deliberately simplified model.
- Return an exact bool: True only for at least one job and a strictly lower parallel estimate. Ties and empty jobs return False. Use integer arithmetic, with no sleeps, timing or pool creation.
- These estimates are non-authoritative. Real startup, per-item encoding, imbalance, payload size and runtime differences need measurement in a supported local process lab.
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.
- large useful work wins model
out = should_parallelize(8, 100, 10, 5, 2) assert type(out) is bool and out is True
- tiny jobs lose to startup
out = should_parallelize(3, 1, 20, 2, 3) assert type(out) is bool and out is False
- ties choose serial
out = should_parallelize(2, 10, 10, 0, 2) assert type(out) is bool and out is False
- partial wave is charged
out = should_parallelize(5, 10, 24, 0, 2) assert type(out) is bool and out is False
- empty and zero-work jobs
for args in [(0, 10, 0, 0, 2), (5, 0, 0, 0, 3), (3, 10, 0, 0, 1)]: out = should_parallelize(*args) assert type(out) is bool and out is False - invalid worker bound always rejects
for workers in [0, -1]: raised = False try: should_parallelize(0, 10, 0, 0, workers) except ValueError: raised = True assert raised
Does True promise that a real process pool is faster?
No. It answers only the stated integer-cost model. Real pools have encoding costs, imbalance and runtime-dependent overhead. The policy takes O(1) arithmetic operations and O(1) extra space under a bounded-integer cost model; arbitrarily large Python integers have size-dependent costs.
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 milestoneAn actual process-pool lab
A process-pool lab must actually cross the OS boundary. Here we first model batching: a batch groups several small jobs so transfer and scheduling costs can be paid less often.
Understand first
If work is too small per call, grouping it can reduce dispatch overhead. Before launching a real local pool, verify the chunk boundaries and output order in a deterministic fixture. Know slices and range; batch size must be a positive integer.
Words you will see
- Batch
- A bounded group of items handled as one unit.
- Dispatch overhead
- Work needed to arrange a job in addition to computing its answer.
- Load balance
- How evenly useful work is distributed among available workers.
Split without losing the tail
range steps through starts zero, two and four. Each slice holds at most two values, so the last batch has just six. Slicing creates new outer lists. Squaring each batch and flattening in batch order keeps all five result positions.
A size of zero is not an empty-work policy; range rejects a zero step. Negative sizes would silently produce no batches here, so a reusable helper must explicitly reject nonpositive sizes. Empty values with a valid size should produce no batches.
Run the actual lab only in the right environment
Use the saved top-level worker and main-guard process lab described in core. To explore batching, make a top-level worker that returns a list of squares for one batch, map it over these batches and flatten after completion. This needs local OS process support; the browser fixture intentionally stays serial.
Larger batches can reduce transfers but make one slow batch dominate completion and use more memory per job. Smaller batches may improve balance while increasing overhead. Compare bounded workloads and peak payload sizes; neither one worker per item nor one giant batch is automatically best.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
size = 2Choose a positive maximum number of items per batch.
batches = [values[start:start + size] for start in range(0, len(values), size)]Copy consecutive slices, including the short tail.
results = [[value * value for value in batch] for batch in batches]Run the same pure calculation serially for each batch.
print(values)Show that creating these batches did not change the original list.
Save the top-level square function in a .py file. Under the main guard, import ProcessPoolExecutor, create it with max_workers=2 and print(list(pool.map(square, values))). Compare results with the serial version, then measure large versus tiny batches. This lab creates OS processes and is intentionally not run by the bounded example verifier.
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.
Use a batch larger than the input.
Try: Set size = 8.
There is one five-item batch and the flattened squares stay unchanged.
Use an empty input.
Try: Set values = [].
Both batch and result lists are empty; no process work is implied.
Before you move on
With seven values and size three, what batch lengths must be preserved?
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
Three, three and one. The short tail is real work, not padding or an error. Empty input instead gives no batches.
Transfer and failure boundaries
A transfer boundary must reject incomplete or malformed results before publishing them. Retrying failed jobs also needs an idempotency policy: repeating a calculation is different from repeating a payment.
Understand first
One worker's failure must not make an incomplete result look complete. Index validation is useful even without processes and keeps boundary rules executable in the browser. The fixture accepts only integer indices and immutable scalar values; it is not an untrusted-data parser.
Words you will see
- Completeness
- Having exactly one valid result for every required job.
- Idempotency
- A repeat operation having the same intended effect as one operation.
- Serialization failure
- An inability to encode or reconstruct an argument or result at a transfer boundary.
Validate before arranging results
dict(records) makes lookup convenient but would silently overwrite a duplicate index. Comparing lengths detects that loss. Comparing the key set with range(count) detects missing, negative and out-of-range indices. Only then does the function publish an ordered list.
The first call is complete despite reversed arrival order. The second lacks index one, and the third repeats index zero. None is an explicit invalid-fixture result, distinct from [] for a valid zero-job collection. A production API may choose an exception instead.
Failures are not permission to repeat side effects
A pure square can be recalculated after failure without charging anyone twice. A job that writes to an external system needs an explicit identity and deduplication or transactional rule. A worker may have finished its side effect before the parent sees a broken connection.
Keep payloads bounded and never unpickle untrusted input. Do not ship live secret-bearing clients or assume inherited connections are valid. A local pool crash, encoding failure or missing result needs a visible failure policy, not hidden partial success. These checks cover ordering policy, not worker reliability.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
by_index = dict(records)Build a candidate lookup, which alone is not validation.
if len(by_index) != len(records) or set(by_index) != set(range(count)):Reject duplicate, missing or unexpected positions.
return [by_index[index] for index in range(count)]Publish values only after full coverage is established.
print(collect([(0, 9)], 2))Show rejection of an apparently plausible partial result.
Keep payloads bounded and choose batch sizes deliberately. A crashed worker or serialization failure is not a valid partial result. Reject untrusted pickle input, avoid moving secret-bearing clients across processes and define retry/idempotency rules for side-effecting tasks.
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.
Supply no jobs.
Try: Add print(collect([], 0)).
It prints [] as a valid complete empty result.
Try an out-of-range identity.
Try: Replace the incomplete call with collect([(0, 9), (2, 16)], 2).
It still prints None: there are two records but not the required two indices.
Before you move on
Is [(0, 7), (2, 8)] a complete result for count two?
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. It has two records but is missing index one and includes unexpected index two. Record count alone is insufficient.
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.