Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 47 / PERFORMANCE AND INTERNALS

Profile time and memory with evidence

Find the expensive work before choosing an optimisation.

AdvancedTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

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.

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.

YOU WILL BE ABLE TO
  • Explain measure a representative workload
  • Apply choose the appropriate profiler
  • Reason about optimise the right boundary
01

Measure a representative workload

A benchmark is a controlled comparison of a named piece of work. Decide what correct work means before asking whether a program is fast.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A report can look faster simply because it skipped records. Fixed inputs and a checked result make an optimisation comparison meaningful before clocks enter the discussion.

Words you will see

Workload
The inputs and operations a comparison covers.
Baseline
The correct version used as the starting comparison.
Metric
The quantity being observed, such as elapsed duration or allocation peak.

Choose the boundary

The example supplies two batches and counts all their entries. len measures entries, not elapsed time. The baseline total is five because both batches contribute. Naming the boundary prevents accidentally comparing one complete report with one inner loop.

A real timing study should state interpreter version, input distribution, warm or cold caches, and whether parsing and printing count. Use a monotonic timer for elapsed duration and repeat trials. Do not invent timing output for this deterministic counting fixture.

Compare equal work

A candidate that drops the second batch does less work and produces the wrong answer. Verify output and input preservation first. Then measure typical and adverse distributions; repeating an unrealistic input does not make it representative.

A benchmark answers a scoped question, not which syntax is universally fastest. A profiler can locate expensive calls; a benchmark compares a defined operation. Keep startup and setup outside the measured region only when the stated metric excludes them.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. batches = [[2, 4], [6, 8, 10]]

    Supply two batches with five entries altogether.

  2. counts = [len(batch) for batch in batches]

    Count both batches without changing them.

  3. total = sum(counts)

    Combine the observed work into five entries.

  4. print(total)

    Report a coverage count, not a duration.

A benchmark needs input size/distribution, runtime version, environment and a meaningful metric. Separate startup, parsing, computation and output. Use repeated measurements and a monotonic timer; one wall-clock run is weak evidence.

Conceptual evidence flow, not a measured profile

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. ContractAll batches must contribute.
  2. CorrectnessCheck five entries and unchanged inputs.
  3. MeasurementOnly then compare repeated durations under a recorded environment.
Predict before you run

What does total represent?

Check workload coverage before measuringPYTHON 3

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 empty batch.

Try: Append [] to batches.

A zero joins counts; total remains five.

Increase the workload.

Try: Append [12] to batches.

The total becomes six; a later timing comparison must use this same input on both versions.

Before you move on

A candidate processes only the first of three equally sized batches. Is its lower elapsed duration evidence of a valid optimisation?

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 changed the workload and omitted required output. Restore equivalent results before comparing repeated measurements.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Choose the appropriate profiler

A call profile attributes work to functions. Self time concerns a function's own work; cumulative time also includes its called functions.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A slow report may spend its budget inside a helper. Counting calls can expose repeated work without pretending that one portable timing number exists.

Words you will see

Profiler
An instrument that records execution events and costs.
Self time
Time attributed to a function excluding its callees.
Cumulative time
Time attributed to a function including its callees.

Read attribution causally

The wrapper calls square three times. cProfile records those calls; pstats exposes the resulting records. The example selects the function by name and displays its total call count, not unstable duration fields or file addresses.

A wrapper can have high cumulative cost because its child performs expensive work. That does not prove that the wrapper's own statements need rewriting. Follow the expensive path and propose one change whose correctness can be checked.

Treat instrumentation as evidence with limits

cProfile measures execution with instrumentation overhead. Short calls can be distorted by that overhead. Confirm a suspected bottleneck with a separate representative benchmark instead of declaring the first profile a verdict.

A call-level profile does not fully explain native allocations, operating-system scheduling or network delays. Use the tool matching the question. This sample requires a host CPython build with cProfile; browser builds may lack it and must show the real import error.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def square(value):

    Define the bounded helper whose calls we want to count.

  2. profiler = cProfile.Profile()

    Create an instrument; no timing result is asserted.

  3. stats = pstats.Stats(profiler).stats

    Read the recorded call data after execution.

  4. print(calls)

    Display the three recorded calls to square.

cProfile identifies call-level CPU time patterns; tracemalloc tracks Python allocations. Neither completely explains native-library memory or operating-system scheduling. Start with a baseline and verify correctness after every optimisation.

Predict before you run

How many square calls are recorded?

Inspect call counts without fabricated timingPYTHON 3

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.

Remove one input.

Try: Change [2, 3, 4] to [2, 3].

The result has two squares and the call count becomes two.

Call the helper twice per item.

Try: Replace square(value) with square(value) + square(value).

There are six calls; output changes too, so this is not an equivalent optimisation.

Before you move on

A parent has little self time but large cumulative time. Which code should you inspect next?

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

Inspect its callees and their call counts. The parent may mostly delegate work; changing its local syntax may not improve the dominant cost.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Inspect Python allocation tracking

Allocation tracking records Python-managed allocations while tracking is active. Current retained allocations and the highest observed level answer different questions.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A batch can briefly need more storage than it keeps. Comparing peak and current tracking helps investigate that distinction without confusing either with whole-process memory.

Words you will see

Allocation
Storage requested for an object or operation.
Current tracked memory
Tracked allocations still present at observation.
Peak tracked memory
The greatest tracked level since tracking started or the peak was reset.

Read the original allocation program

The original program starts tracemalloc, builds 1000 integers in a list and then reads current and peak. len reports 1000. The comparison prints True because peak cannot be below current in that observation, and neither count is negative.

The output deliberately avoids exact byte counts. Object representation, interpreter version and surrounding work affect measured allocations. Starting tracking after building the list would miss earlier allocations and answer a different question.

Know the boundary of the instrument

tracemalloc is not a full resident-memory meter. Native libraries and operating-system accounting may need other tools. Repeated comparable snapshots can help locate growing allocations, but an allocation location alone does not identify every owner retaining the object.

Use a host Python with tracemalloc support for this program. Some browser Python builds omit or restrict it; preserve the real failure instead of supplying fake bytes or a successful fallback. Tracking itself has overhead, so record whether it was enabled during performance comparisons.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. tracemalloc.start()

    Enable tracking before constructing the values.

  2. values = [number for number in range(1000)]

    Retain a list containing 1000 numbers.

  3. current, peak = tracemalloc.get_traced_memory()

    Observe the two tracked quantities.

  4. tracemalloc.stop()

    Disable tracking after the observation.

The fixture checks the relationship between peak and current tracked allocations, not an environment-specific byte count.

Predict before you run

Why is the second output True?

Inspect Python allocation trackingPYTHON 3

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 retained length.

Try: Replace range(1000) with range(10).

The first line becomes 10; the ordering relationship remains true.

Observe an empty list.

Try: Replace range(1000) with range(0).

Length becomes zero; tracking overhead and other allocations need not be zero.

Before you move on

You start tracking after building a large cache. Does a small current count prove that the cache uses little memory?

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 cache's earlier allocations were outside the tracking interval. Track before the operation and inspect ownership as well as comparable snapshots.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Turn a slow-program complaint into a measurement question

Begin with an observable target such as elapsed time for one complete report or peak memory while handling a bounded batch. Record input size, distribution, interpreter build, dependencies, and whether caches are warm. A benchmark that excludes parsing cannot explain an end-to-end parsing regression. Establish a correct baseline output first, because a version that silently omits records can look impressively fast while doing the wrong job.

Separate startup, input acquisition, transformation, and output. Repeated monotonic-clock measurements help expose noise, but repetition does not repair an unrepresentative fixture. Compare both typical and adverse inputs: repeated keys exercise a small aggregation, while distinct keys grow its dictionary. Keep benchmark setup outside the measured operation when setup is not part of the stated user-facing metric, and document that exclusion rather than hiding it.

Read a profile as a causal lead rather than a verdict

Use cProfile to discover call patterns and cumulative costs, then inspect the expensive path. A function with high cumulative time may mostly wait for work in its callees, whereas high self time points toward work within the function. Instrumentation has overhead and can perturb short calls. Confirm a proposed bottleneck with a focused experiment instead of rewriting every function that appears near the top of a report.

Suppose a report loops over records and checks each topic against a growing list. A profile may implicate the enclosing aggregation rather than explicitly announcing a quadratic algorithm. Count the repeated scans, replace membership state with an appropriate set or dictionary, and compare outputs before measuring again. If elapsed time is dominated by remote waiting, a faster local loop may barely affect the overall result; improve the boundary that actually consumes the budget.

Distinguish allocation peaks from retained ownership

The tracemalloc example creates 1000 values and checks that peak tracked allocation is at least current tracked allocation, with both nonnegative. It intentionally avoids a fixed byte count because runtime representation and surrounding allocations vary. Current describes tracked allocations still present at observation; peak records the highest tracked level since tracking began or the peak was reset. Neither number is automatically the operating system's resident memory measurement.

For growth across requests, take comparable snapshots after repeated batches and inspect allocation differences alongside cache counts and task ownership. A large temporary list may produce a high peak but disappear after processing. A global registry can retain small increments forever. Native extension allocations, allocator reuse, and operating-system accounting require additional evidence; failure of resident memory to immediately fall is not by itself proof that Python objects remain reachable.

Evaluate one optimization with a rollback criterion

Write a hypothesis with a predicted consequence: streaming should remove the list of all rows while leaving memory proportional to distinct groups. Change one boundary, rerun behavioral tests, and measure both elapsed time and peak memory. Streaming can introduce more calls or slower I/O even while reducing retention. A successful optimization report states which resource improved, which costs increased, and which input assumptions make the result useful.

Reject a change if it breaks ordering, error reporting, freshness, or input ownership even when its benchmark improves. Keep the baseline available so measurements can be reproduced after a dependency or interpreter upgrade. For a cache optimization, measure misses and entry sizes as well as hits. For a data-structure change, include adversarial cardinality and key sizes rather than treating expected constant-time dictionary access as an unconditional guarantee.

Transfer question: A streaming rewrite lowers tracked peak allocations, but process memory and user latency remain high. What evidence should you collect next?

First verify equal outputs and compare the same workload phase. Inspect retained group cardinality, pending tasks, caches, and the lifetime of the input adapter. Compare tracemalloc snapshots with process-level memory observations to see whether growth is outside tracked Python allocations or reflects allocator retention. Break latency into acquisition, transformation, and output; streaming may still wait on slow storage. Test repeated bounded batches and a distinct-key workload separately. Do not prescribe garbage collection or more workers until those observations identify whether the constraint is ownership, native buffers, resource waiting, or computation.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Does tracemalloc necessarily explain all native-library memory?
TRANSFER THE IDEA

Rebuild: Inspect Python allocation tracking

Without copying the worked code, reproduce its observable contract: The fixture checks the relationship between peak and current tracked allocations, not an environment-specific byte count. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

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.

MAKE THE RULE WORK ON NEW INPUTS

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.

Return a value, do not only print itPYTHON 3

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

Guided: summarize an observation series

Summarize already supplied nonnegative integer observations. This is data processing, not a timing instrument.

The contract

  • Accept a list of nonnegative exact integers; test fixtures stay within this domain.
  • Return a fresh dict with count, total and peak; an empty series has peak zero.
  • Do not mutate or retain the caller's list. Values are observations, with no claimed units or measured runtime.
Guided: summarize an observation seriesPYTHON 3

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.

  1. ordinary series
    import copy
    
    source = [2, 5, 3]
    before = copy.deepcopy(source)
    result = summarize_samples(source)
    assert type(result) is dict, "Wrong result type"
    expected = {"count": 3, "total": 10, "peak": 5}
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert result is not source, "Return a fresh container"
    
  2. empty series
    import copy
    
    source = []
    before = copy.deepcopy(source)
    result = summarize_samples(source)
    assert type(result) is dict, "Wrong result type"
    expected = {"count": 0, "total": 0, "peak": 0}
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert result is not source, "Return a fresh container"
    
  3. repeated observations
    import copy
    
    source = [4, 4]
    before = copy.deepcopy(source)
    result = summarize_samples(source)
    assert type(result) is dict, "Wrong result type"
    expected = {"count": 2, "total": 8, "peak": 4}
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert result is not source, "Return a fresh container"
    
  4. zero boundary
    import copy
    
    source = [0]
    before = copy.deepcopy(source)
    result = summarize_samples(source)
    assert type(result) is dict, "Wrong result type"
    expected = {"count": 1, "total": 0, "peak": 0}
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert result is not source, "Return a fresh container"
    
  5. peak is not last
    import copy
    
    source = [9, 1]
    before = copy.deepcopy(source)
    result = summarize_samples(source)
    assert type(result) is dict, "Wrong result type"
    expected = {"count": 2, "total": 10, "peak": 9}
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert result is not source, "Return a fresh container"
    
  6. result owns its mapping
    import copy
    
    source = [1, 2]
    before = copy.deepcopy(source)
    result = summarize_samples(source)
    assert type(result) is dict, "Wrong result type"
    expected = {"count": 2, "total": 3, "peak": 2}
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    assert result is not source, "Return a fresh container"
    result["total"] = -1
    assert source == before
    assert all(type(value) is int for value in [result["count"], result["peak"]])
    Why not divide total by count here?

    The contract asks for total, not mean. A single scan uses O(n) work and O(1) result fields; no clock or allocation claim follows.

    GUIDED PRACTICE

    Guided: preserve first-seen observations

    Replace repeated list membership with separate set membership while preserving the original first-appearance order.

    The contract

    • Input is a finite list of strings; equality determines duplicates.
    • Return a new list with one occurrence per distinct string in first-seen order, not alphabetical order.
    • Do not mutate the input; immutable strings may be shared. Empty input returns a fresh empty list.
    Guided: preserve first-seen observationsPYTHON 3

    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.

    1. arrival order
      import copy
      
      source = ["b", "a", "b"]
      before = copy.deepcopy(source)
      result = first_observations(source)
      assert type(result) is list, "Wrong result type"
      expected = ["b", "a"]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    2. empty observations
      import copy
      
      source = []
      before = copy.deepcopy(source)
      result = first_observations(source)
      assert type(result) is list, "Wrong result type"
      expected = []
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    3. all repeated
      import copy
      
      source = ["x", "x", "x"]
      before = copy.deepcopy(source)
      result = first_observations(source)
      assert type(result) is list, "Wrong result type"
      expected = ["x"]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    4. empty string is data
      import copy
      
      source = ["", "x", ""]
      before = copy.deepcopy(source)
      result = first_observations(source)
      assert type(result) is list, "Wrong result type"
      expected = ["", "x"]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    5. case sensitive
      import copy
      
      source = ["a", "A", "a"]
      before = copy.deepcopy(source)
      result = first_observations(source)
      assert type(result) is list, "Wrong result type"
      expected = ["a", "A"]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    6. fresh ordered output
      import copy
      
      source = ["z", "a"]
      before = copy.deepcopy(source)
      result = first_observations(source)
      assert type(result) is list, "Wrong result type"
      expected = ["z", "a"]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      result.append("new")
      assert source == before
      assert all(type(value) is str for value in result)
      What does the set cost?

      For n strings and u distinct values, ordinary average hash-table work is O(n), ignoring string hash cost, with O(u) membership and output storage. This is not a measured speed claim.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: retain only the last k batch totals

      The requirement changes from retaining every result to keeping a bounded recent window, including repeated totals.

      The contract

      • Input is a finite list of integer lists and a nonnegative exact integer k.
      • Return the last k per-batch sums in arrival order; k=0 returns []; do not deduplicate.
      • Do not change outer or inner input lists. Use a bounded deque so retained intermediate totals are O(k).
      Transfer: retain only the last k batch totalsPYTHON 3

      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.

      1. last two batches
        import copy
        
        source = [[1], [2, 3], [4]]
        before = copy.deepcopy(source)
        result = recent_totals(source, 2)
        assert type(result) is list, "Wrong result type"
        expected = [5, 4]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      2. no batches
        import copy
        
        source = []
        before = copy.deepcopy(source)
        result = recent_totals(source, 3)
        assert type(result) is list, "Wrong result type"
        expected = []
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      3. repeated totals remain
        import copy
        
        source = [[2], [1, 1], [2]]
        before = copy.deepcopy(source)
        result = recent_totals(source, 2)
        assert type(result) is list, "Wrong result type"
        expected = [2, 2]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      4. zero capacity
        import copy
        
        source = [[1], [2]]
        before = copy.deepcopy(source)
        result = recent_totals(source, 0)
        assert type(result) is list, "Wrong result type"
        expected = []
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      5. empty batch contributes zero
        import copy
        
        source = [[], [-2, 1]]
        before = copy.deepcopy(source)
        result = recent_totals(source, 5)
        assert type(result) is list, "Wrong result type"
        expected = [0, -1]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      6. result cannot alter rows
        import copy
        
        source = [[8], [9]]
        before = copy.deepcopy(source)
        result = recent_totals(source, 1)
        assert type(result) is list, "Wrong result type"
        expected = [9]
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        result.append(10)
        assert source == before
        assert all(type(value) is int for value in result)
        Does bounded retention avoid reading every row?

        No. Every entry must contribute to its row's sum. For m total numbers and b rows, work is O(m+b); the deque retains O(min(k,b)) totals, plus its final list.

        A GOOD PLACE TO PAUSE

        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 milestone

        References often explain retention

        An object stays reachable while an owner still references it. A cache can keep data alive after a local variable stops being used.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Memory growth across requests often follows ownership rather than a failure of garbage collection. Drawing the remaining reference explains why collection cannot remove useful-looking cache entries.

        Words you will see

        Reachable
        Accessible by following references from live program state.
        Owner
        A live object or name retaining another object.
        Retention
        Keeping an object alive beyond the point the application needs it.

        Follow the remaining edge

        payload and cache['latest'] initially reference the same list. Deleting payload removes only that name. The cache still owns the list, so its two entries remain readable. pop removes the cache's entry and returns the list to a new owner named released.

        This is a conceptual ownership experiment, not a heap measurement. Printing the cache size after pop proves the mapping is empty, not that every reference to the old list has disappeared. released still refers to it.

        Give retained state a policy

        Use a size bound, expiration or explicit eviction when a cache should forget data. Calling garbage collection does not implement that policy: reachable cache values are not garbage. Test repeated requests and inspect entry counts alongside allocation snapshots.

        A weak reference can avoid ownership in some designs but has type and lifetime constraints, and a disappearing value may violate the cache's contract. Prefer explicit ownership first. Copying a list would make a second outer container but still requires deciding who retains each copy.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. cache["latest"] = payload

          Give the cache a reference to the same list.

        2. del payload

          Remove one name, not the cache's ownership.

        3. released = cache.pop("latest")

          Transfer the retained list out of the mapping.

        4. print(released)

          Show that the returned list still has an owner.

        A callback, cache, task or global collection may retain an object long after the local function returns. Inspect ownership paths and growth over repeated operations. Garbage collection cannot reclaim a reachable object merely because your application no longer needs it.

        Predict before you run

        After del payload, what remains in the cache?

        A cache outlives a local namePYTHON 3

        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 another owner.

        Try: Assign backup = released, then del released and print(backup).

        The list remains available through backup.

        Evict earlier.

        Try: Move cache.pop("latest") before the first cache["latest"] read.

        The later bracket read raises KeyError, revealing the changed lifetime contract.

        Before you move on

        A completed request's result remains in a global dictionary. Can cyclic collection remove it while that entry is still reachable?

        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. Remove or bound the retained entry according to the cache policy. Collection is not permission to discard reachable program state.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Optimise the right boundary

        An algorithmic improvement removes repeated work rather than merely shortening syntax. Membership state can trade extra storage for fewer scans.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Keeping the first occurrence of each value with a growing list can repeatedly scan prior entries. A separate set can answer whether a hashable value has been seen.

        Words you will see

        Hashable
        Usable as a set member or dictionary key with a stable hash and equality contract.
        Average-case work
        Expected cost under ordinary hash-table behavior, not a universal worst-case promise.
        Streaming
        Processing entries in arrival order without requiring every intermediate result to stay live.

        Separate order from membership

        The list result preserves first appearance. The set seen answers membership; it is not the output order. For b, a, b, the third value is skipped because b is already in seen, while the result remains b followed by a.

        For n hashable values and u distinct values, the ordinary average total work is O(n) and retained membership storage is O(u), plus the output. A list-only membership approach can require O(n squared) comparisons when many distinct values arrive.

        Preserve the actual contract

        Replacing the entire result with a sorted set loses first-appearance order. Replacing it with an unordered set also changes type. Test output, duplicates and input ownership before benchmarking a candidate.

        Lists inside the input are not hashable and raise TypeError in this design. A list-based equality scan remains an alternative for unhashable values, with different cost. Streaming lowers intermediate storage only when the consumer and required result do not retain all outputs.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. seen = set()

          Start with no membership history.

        2. result = []

          Keep a separate ordered output.

        3. if value not in seen:

          Accept only the first equal hashable value.

        4. result.append(value)

          Preserve first-arrival order rather than set traversal order.

        An O(n squared) membership loop may benefit more from a set than from local syntax changes. Streaming can trade throughput for memory. Re-run representative tests and document the new memory/time trade-off rather than advertising one number as universally faster.

        Predict before you run

        What order is printed?

        Use a set for membership and a list for orderPYTHON 3

        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.

        Move the first appearance.

        Try: Change values to ["a", "b", "a"].

        The result becomes a then b.

        Test the boundary.

        Try: Change values to [].

        No loop body executes and the result is an empty list.

        Before you move on

        The changed input contains nested lists. Can this set-based method handle it unchanged?

        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. Lists are unhashable. Define a safe immutable key or use equality scanning if nested-list equality is the required contract, then reconsider costs.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        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.

        REFLECT, THEN CONTINUE

        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.

        Your account

        Loading account...

        Sign in to save your work across devices.