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 56 / SCENARIO-BASED QUESTIONS

Scenario: process a 10 GB report with limited memory

A reporting script reads an entire file, splits it into a list and then builds several transformed lists. It is killed for memory usage on a 10 GB input even though the final report contains only a few counters.

AdvancedScenario 18 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: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Build a diagnosis from evidence
  • Compare a repair with its trade-offs
  • Test the changed behaviour
DIAGNOSTIC CASE FILE

Follow the evidence.

A reporting script reads an entire file, splits it into a list and then builds several transformed lists. It is killed for memory usage on a 10 GB input even though the final report contains only a few counters.

Observed evidence

  • Peak memory grows with the complete input size.
  • Several intermediate collections coexist.
  • The required output can be updated one record at a time.

Investigation sequence

  1. Identify which operations materialise the entire input.
  2. Write a streaming transformation with bounded output state.
  3. Test invalid records, line endings and high-cardinality grouping rather than only a tiny successful file.

Challenge the repair

  • Test blank, negative and malformed rows with actionable row numbers.
  • How would you aggregate millions of distinct keys under a strict memory cap?
01

Read the incident, not just the error

Materialising input means keeping all its records in a collection. Several materialised stages can coexist even when the final answer is only one number.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The reported 10 GB failure suggests full-input retention, but a small safe fixture can reveal the allocation pattern without attempting a huge file in the browser.

Words you will see

Materialise
Build a collection containing all values now instead of visiting them one at a time.
Intermediate
A result kept between input and final output.
Peak retention
The live data retained at the busiest point; not the same as raw file size.

Reproduce the shape, not the dangerous size

The fixture holds text, split row strings and parsed integers at the same time. Printing their lengths establishes that separate collections exist; it does not measure their bytes. The browser does not open a 10 GB file here.

The symptom alone does not prove which allocation caused a memory kill. Other hypotheses include one enormous record, an unbounded cache, or many distinct grouping keys. Trace where each collection is built and how long it remains referenced before changing the parser.

Remove retention only when the output allows it

A sum needs the next value and the running total, not a history of all values. A detail report requiring every row has a different storage contract. Iterating lines helps only if later stages also avoid collecting everything.

StringIO owns an in-memory text fixture. Its input already occupies memory, so a successful run is not proof of bounded total process memory or successful large-file processing. It lets us test the same line-iteration interface without host data, disk access or network.

The original example, step by step

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

  1. text = source.read()

    Read the entire remaining fixture into one string.

  2. rows = text.splitlines()

    Retain a list of all row strings.

  3. values = [int(row) for row in rows]

    Build another complete list while the earlier objects remain named.

  4. print(sum(values))

    The final answer needs far less information than those retained collections.

A reporting script reads an entire file, splits it into a list and then builds several transformed lists. It is killed for memory usage on a 10 GB input even though the final report contains only a few counters.

Conceptual retention boundary, not measured memory

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

  1. Beforeread → full text → all row strings → all integers coexist.
  2. StreamRead one line and parse one value.
  3. UpdateReplace the running total; release the previous line when no longer referenced.
  4. BoundaryLargest line, parser buffers, integer size and output groups still matter.
Predict before you run

Does the final sum require retaining all parsed integers?

See the materialisation chainPYTHON 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 the integer-list stage.

Try: Replace the values assignment and both print statements with print(sum(int(row) for row in rows)).

It still prints 35. The integer list is avoided, but rows and text still retain all input.

Check the empty boundary.

Try: Use StringIO('').

Both lengths and the sum become zero; that does not change the large-input storage pattern.

Before you move on

Would replacing the values comprehension with list(map(int, rows)) fix full-input retention?

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. list still materialises every converted value, and rows and text remain referenced. Changing syntax has not changed the retention boundary.

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

Investigate before changing code

A streaming function borrows a line source and updates its result as lines arrive. It should not secretly rewind, close, or read ahead beyond its contract.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Separating parsing from opening a resource makes the repair testable and keeps resource lifetime with the caller that owns it.

Words you will see

Borrowed stream
A source supplied by a caller that remains responsible for closing it.
Cursor
The current reading position in a stream.
Fail-fast
Stop at the first invalid record instead of quietly skipping it.

Use an experiment that could reject the diagnosis

Read one line from StringIO and observe that the next read starts at the next line. This establishes advancing state. list(source) consumes every remaining line, so wrapping iteration in list is not a streaming repair.

A useful regression source can forbid read(), record which lines were requested, and fail if the parser reads beyond an error. This catches accidental materialisation and over-consumption even when a tiny final sum looks correct. Printed output alone does not test those behaviors.

Keep ownership explicit on errors too

The caller may need the stream after a prefix report or want to inspect a failure position. The parser should leave it open and at its actual consumed position. An adapter that opens a real file should close it with a context manager; the borrowed core should not close someone else's source.

Line iteration still holds one current line, which can be very long. It also does not resolve a chosen blank-line or negative-value policy. Document those policies before optimizing, and include row numbers without dumping entire potentially sensitive records into diagnostics.

The original example, step by step

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

  1. source = StringIO('10\n20\n5\n')

    The fixture's caller owns a local stream.

  2. print(next(source).strip())

    Each call consumes one next line; strip removes its line ending for display.

  3. print(source.closed)

    Reading lines did not close the borrowed resource.

Identify which operations materialise the entire input. Write a streaming transformation with bounded output state. Test invalid records, line endings and high-cardinality grouping rather than only a tiny successful file.

Predict before you run

What does the second next read?

Observe the stream cursorPYTHON 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.

Consume the rest deliberately.

Try: Add print(list(source)).

It prints ['5\n']; the first two lines are already consumed.

Close under the owner's control.

Try: Add source.close() followed by print(source.closed).

The added print is True. Later reads would raise ValueError because the resource is closed.

Before you move on

After these two reads, what should next(source).strip() return, and who should close source?

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 '5'. The caller that created the stream owns closing it; a helper borrowing it should neither rewind nor close it without agreement.

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

A repair you can explain

An incremental total keeps an aggregate rather than every row. Validate each parsed value before adding it so invalid data does not silently become part of the answer.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The incident's final report needs only total minutes. A line-at-a-time algorithm removes unnecessary lists while preserving the original numeric rule.

Words you will see

Aggregate
A compact result updated from many inputs, such as a total.
enumerate
A helper pairing each input with a counter; start=1 makes the counter a human row number.
Validation
Checking whether a value satisfies the report's stated rules.

Read the preserved repair

total starts at zero. enumerate yields each line with a one-based row number. strip removes surrounding whitespace; int parses the remaining text. Negative minutes raise ValueError with the offending row; otherwise += adds the value. Empty input returns zero.

This original source does not silently skip blanks: int('') raises ValueError. Its malformed-text error is Python's conversion message rather than the custom row message. A stricter production contract may wrap conversion errors to add consistent row context, as practice below asks you to do.

State the real cost and lifetime

For n lines this is one traversal; parsing work also depends on character counts. Extra state includes the current line and growing Python integer total. Do not claim exact constant bytes: an unusually long line or a huge integer still costs storage.

The function borrows lines and never closes them. A surrounding adapter owns opening, encoding and closing a real file. StringIO is an offline line source, not a measured filesystem workload. Materialising first may be reasonable for small data requiring later repeated access, but is unnecessary for this total.

The original example, step by step

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

  1. for number, line in enumerate(lines, start=1):

    Visit one line and carry a one-based diagnostic position.

  2. value = int(line.strip())

    Remove surrounding whitespace and parse an integer.

  3. if value < 0:

    Reject a value outside the nonnegative-minutes rule.

  4. total += value

    Keep only the updated aggregate, not a history of values.

  5. return total

    Return an integer even for no lines: zero.

StringIO is an offline fixture for the same line-iteration contract used by an open file. The algorithm retains a running total rather than all input rows or transformed lists.

Predict before you run

What does an empty line source produce?

Aggregate a stream incrementallyPYTHON 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.

Reproduce a validation failure.

Try: Replace the fixture with '10\n-2\n5\n'.

The run raises Negative minutes at row 2; no final total prints.

Test whitespace without changing the rule.

Try: Use ' 10 \n20\n0\n'.

strip permits surrounding spaces and zero is valid, giving 30.

Before you move on

What happens for '10\n-2\n5\n', and is the third line consumed?

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

The explicit check raises ValueError for row 2 before adding -2. Iteration stops there, so the third line is not requested by this function.

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

Reproduce the materialization chain on a smaller input

The 10 GB failure begins with reading the whole file, splitting it, and retaining multiple transformed lists. Reproduce the same allocation pattern using a safely bounded fixture and increasing input sizes. Record which objects coexist at peak usage. The raw file size understates the likely footprint because decoded strings, list references, integer objects, and allocator overhead add memory. A small successful run does not disprove a design whose storage grows with every input record.

Form competing hypotheses before rewriting: full-file retention, an unexpectedly long record, unbounded distinct groups, or a cache outside parsing. Trace where each collection is created and released. Compare tracked Python allocations with process-level observations if native parsing buffers are involved. A memory kill may leave no ordinary Python traceback, so preserve workload size and stage progress as safe evidence without logging the entire input or exposing personal record contents.

Translate the output contract into incremental state

The reference total_minutes iterates text lines, strips each line, converts it to an integer, rejects negative values, and updates one running total. The StringIO values 10, 20, and 5 produce 35. No previous line is required to compute the next update. This changes retained algorithmic state from all records to a current line and a total, while still performing O(n) record-processing work for n lines.

State the real bound carefully. Memory includes the largest current line, parser buffers, and the total's integer representation, which can grow with the sum. A fixed-size aggregate is not a license to accept an unlimited line length. If the report instead groups by topic, the dictionary grows with distinct topics. Streaming input and bounded output state are separate properties; a generator wrapped around an unbounded aggregation does not make the entire program constant-memory.

Repair parsing and ownership without hiding corruption

Keep file opening in an adapter that owns encoding, path policy, and closing; let the core accept a line iterable. StringIO is an offline stand-in for that contract, not evidence that a 10 GB filesystem read completed. Decide whether blank lines are invalid or intentionally ignored and document that rule. The current conversion rejects malformed text, while the explicit negative check adds a row number; extend actionable row context consistently at the adapter or parser boundary.

Choose fail-fast or explicitly partial reporting before implementation. Silently skipping bad rows can produce plausible but wrong totals. If retaining errors, cap both their number and contextual size. CSV with quoted newlines requires a CSV parser rather than arbitrary line splitting, and one large JSON array requires an appropriate parsing strategy rather than pretending it is JSON lines. The streaming unit must match the format's actual record framing.

Verify boundedness and choose spill strategies when needed

Test empty input, zero, trailing line endings, blanks, malformed text, and a negative value after valid rows. Assert that an invalid input does not return a success-shaped partial total. Use a one-pass iterable to show the function does not require length or repeated traversal. A growth experiment with bounded record size can support the memory argument, but inspect the implementation as well because a tiny fixture cannot reveal every accidental list conversion.

For millions of distinct grouping keys, choose partitioned aggregation, external sorting, or a database with explicit resource policy. Partitioning must preserve equal-key grouping and account for oversized partitions; external sorting uses disk and cleanup; a database introduces transactions and query costs. Bound intermediate storage and define failure cleanup before promising a strict cap. The correct alternative depends on whether the input can be replayed and whether exact complete results are required.

Transfer question: A line-streaming topic report still runs out of memory when every row has a different topic. What repair follows from that evidence?

The input is streaming but the output dictionary is not bounded: k distinct topics require O(k) entries. Impose a documented cardinality limit or move aggregation to a spill strategy such as external sorting or a database. For external sorting, create bounded sorted runs, merge equal keys, and remove intermediate files on both success and failure. Test high-cardinality data separately from repeated topics and include disk exhaustion or interrupted output behavior. Do not merely replace the loop with a generator; the retained dictionary remains the same. Exact complete output for unlimited keys must consume storage somewhere.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

What should you do before adopting this repair?
TRANSFER THE IDEA

Recreate the repair independently

Test blank, negative and malformed rows with actionable row numbers. Start from the symptoms and write your own regression assertion before opening the reference.

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

Stream a strict minutes total

Extend the original total with consistent row context while retaining its incremental behavior.

The contract

  • Borrow an iterator of text lines. Return a built-in int total of nonnegative int(line.strip()) values; empty input returns 0. Blank and malformed lines are invalid.
  • Raise ValueError containing 'row N' for the first malformed or negative row, counting from 1. Consume the bad row but do not request the next one.
  • Use one pass with no whole-input read, list or rewind. Do not close the borrowed source. Parsing follows Python int syntax, not a custom CSV grammar.
Stream a strict minutes totalPYTHON 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. Normal borrowed stream
    from io import StringIO
    s = StringIO('10\n20\n5\n')
    r = checked_minutes(s)
    assert type(r) is int and r == 35 and not s.closed and list(s) == []
  2. Empty input
    from io import StringIO
    s = StringIO('')
    r = checked_minutes(s)
    assert type(r) is int and r == 0 and not s.closed and list(s) == []
  3. Repeated values and whitespace
    from io import StringIO
    s = StringIO(' 2 \r\n2\n0\n')
    r = checked_minutes(s)
    assert type(r) is int and r == 4 and not s.closed and list(s) == []
  4. Malformed cursor boundary
    from io import StringIO
    s = StringIO('4\noops\n99\n')
    try:
        checked_minutes(s)
    except ValueError as e:
        assert 'row 2' in str(e) and not s.closed and next(s) == '99\n'
    else:
        raise AssertionError('malformed row accepted')
  5. Negative cursor boundary
    from io import StringIO
    s = StringIO('-1\n8\n')
    try:
        checked_minutes(s)
    except ValueError as e:
        assert 'row 1' in str(e) and not s.closed and next(s) == '8\n'
    else:
        raise AssertionError('negative row accepted')
  6. No eager traversal before blank error
    seen = []
    def rows():
        seen.append(1)
        yield '3\n'
        seen.append(2)
        yield '\n'
        raise AssertionError('read beyond invalid row')
    s = rows()
    try:
        checked_minutes(s)
    except ValueError as e:
        assert 'row 2' in str(e) and seen == [1, 2] and s.gi_frame is not None
    else:
        raise AssertionError('blank row accepted')
    What is the memory claim here?

    The algorithm avoids retaining all rows, but keeps the current line and total, whose sizes can grow. The borrowed StringIO fixture itself already owns the supplied text; it is not a large-file memory measurement.

    GUIDED PRACTICE

    Compute total and count in one streaming pass

    Produce two aggregates, with an explicit policy that ignores blank lines.

    The contract

    • Borrow an iterator of text lines and return a built-in tuple (total, count), both built-in ints. Count valid records, not physical lines; empty or all-blank input returns (0, 0).
    • Ignore lines whose strip() is empty. Nonblank lines use int conversion and must be nonnegative; malformed or negative data raises ValueError containing the physical 'row N'.
    • One incremental pass, no whole-input collection, rewind or closing. On error do not consume beyond the invalid row; duplicates count separately.
    Compute total and count in one streaming passPYTHON 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. Two numeric aggregates
      from io import StringIO
      s = StringIO('10\n20\n5\n')
      r = minute_summary(s)
      assert type(r) is tuple and r == (35, 3) and all(type(x) is int for x in r) and not s.closed and list(s) == []
    2. Empty summary
      from io import StringIO
      s = StringIO('')
      r = minute_summary(s)
      assert type(r) is tuple and r == (0, 0) and all(type(x) is int for x in r) and not s.closed
    3. Blanks are not records
      from io import StringIO
      s = StringIO('\n  \r\n')
      r = minute_summary(s)
      assert type(r) is tuple and r == (0, 0) and all(type(x) is int for x in r) and not s.closed and list(s) == []
    4. Duplicates and zero count
      from io import StringIO
      s = StringIO('2\n\n2\n0\n')
      r = minute_summary(s)
      assert type(r) is tuple and r == (4, 3) and all(type(x) is int for x in r) and not s.closed and list(s) == []
    5. Physical row on malformed data
      from io import StringIO
      s = StringIO('\n4\nbad\n9\n')
      try:
          minute_summary(s)
      except ValueError as e:
          assert 'row 3' in str(e) and not s.closed and next(s) == '9\n'
      else:
          raise AssertionError('bad row accepted')
    6. Negative stops without eager reading
      seen = []
      def rows():
          seen.append(1)
          yield '\n'
          seen.append(2)
          yield '-3\n'
          raise AssertionError('over-consumed')
      s = rows()
      try:
          minute_summary(s)
      except ValueError as e:
          assert 'row 2' in str(e) and seen == [1, 2] and s.gi_frame is not None
      else:
          raise AssertionError('negative accepted')
      Why not run total and count as two passes over lines?

      The first pass would exhaust a single-pass source. Updating two integer aggregates together avoids replay and detail retention; integer and current-line sizes still matter.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: leave the rest of the report unread

      The requirement is now a bounded physical-line preview, not a complete report. A later consumer owns the remainder.

      The contract

      • Borrow an iterator of text lines and an integer limit. Return the built-in int total from at most limit physical lines, using the strict nonnegative int(line.strip()) policy.
      • Zero returns 0 without requesting any line. Negative limit raises ValueError before touching the iterator. Stop early at exhaustion; never read a limit-plus-one line.
      • Malformed, blank or negative consumed lines raise ValueError containing one-based 'row N' relative to this call. Leave the borrowed iterator open at the consumed position; invalid data after the prefix is not examined.
      Transfer: leave the rest of the report unreadPYTHON 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. Prefix leaves invalid tail
        from io import StringIO
        s = StringIO('2\n3\nbad\n')
        r = prefix_minutes(s, 2)
        assert type(r) is int and r == 5 and not s.closed and next(s) == 'bad\n'
      2. Zero reads nothing
        seen = []
        def rows():
            seen.append('read')
            yield 'bad\n'
        s = rows()
        r = prefix_minutes(s, 0)
        assert type(r) is int and r == 0 and seen == [] and s.gi_frame is not None and next(s) == 'bad\n'
      3. Short empty source
        from io import StringIO
        s = StringIO('')
        r = prefix_minutes(s, 4)
        assert type(r) is int and r == 0 and not s.closed
      4. Repeated rows and exact boundary
        from io import StringIO
        s = StringIO('2\n2\n0\n9\n')
        r = prefix_minutes(s, 3)
        assert type(r) is int and r == 4 and not s.closed and next(s) == '9\n'
      5. Error inside prefix
        from io import StringIO
        s = StringIO('1\n-2\n8\n')
        try:
            prefix_minutes(s, 3)
        except ValueError as e:
            assert 'row 2' in str(e) and not s.closed and next(s) == '8\n'
        else:
            raise AssertionError('negative prefix row accepted')
      6. Negative limit reads nothing
        seen = []
        def rows():
            seen.append('read')
            yield '8\n'
        s = rows()
        try:
            prefix_minutes(s, -1)
        except ValueError:
            assert seen == [] and s.gi_frame is not None and next(s) == '8\n'
        else:
            raise AssertionError('negative limit accepted')
        Why can enumerate followed by if number > limit: break be wrong?

        The loop already requests that extra line before the condition runs. Pull at most limit times or use islice carefully. Work is proportional to consumed text, with only the current line and growing total retained.

        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

        The underlying mechanism

        Streaming input does not bound output state. A grouping dictionary grows with the number of distinct keys even when records arrive one at a time.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        After eliminating full-file lists, a report can still exceed its resource budget if every record introduces a new group.

        Words you will see

        Cardinality
        The number of distinct group keys.
        Working state
        Data the algorithm retains while processing the next input.
        Partitioning
        Splitting records into smaller groups that can be handled separately.

        Watch the output grow independently

        The generator expression supplies three records one at a time. get(key, 0) reads the old total or zero; assignment stores the updated total. Two a rows share one entry, while b creates a second entry. The final result therefore contains two keys, not three records.

        If every key were different, the dictionary would retain one entry per row. A generator at the input boundary cannot remove that output requirement. Keys and growing totals also have sizes; the number of entries alone is not a byte measurement.

        Change the report or move its storage

        If keys come from a known small vocabulary, in-memory grouping may be appropriate. If the vocabulary is unbounded, consider a group-count limit with explicit rejection, partitioning, external sorting, or database aggregation in a separate environment.

        Those alternatives cost extra passes, storage, deployment or changed failure behavior. Silently dropping unfamiliar keys changes the report. In this browser sample we use only supplied in-memory values; no database, external file or large-memory claim is being simulated.

        The original example, step by step

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

        1. records = ((key, value) for key, value in [('a', 2), ('b', 3), ('a', 4)])

          Iterate a tiny supplied fixture; it is not an external data source.

        2. totals[key] = totals.get(key, 0) + value

          Update one entry per distinct key.

        3. print(len(totals))

          Show two groups; streaming did not eliminate output storage.

        Streaming input does not guarantee bounded memory if the output accumulates every distinct key. Account for parser buffers, maximum record length, error samples and any caches. Python object overhead can exceed the raw input representation.

        Predict before you run

        How many dictionary entries survive three input records?

        Count groups, not just rowsPYTHON 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.

        Increase cardinality.

        Try: Change the final a key to c.

        The totals contain three entries rather than two.

        Keep one group but grow its value.

        Try: Use a as every key.

        One entry remains with total 9; integer magnitude still has a storage cost.

        Before you move on

        If the third record is ('c', 4) instead, which resource bound changes?

        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

        Cardinality rises from two groups to three, so retained dictionary state grows. The input traversal remains one pass, but its output state has changed.

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

        Alternatives and operational trade-offs

        A report must state what happens to corrupt input. Failing early with a row number is different from skipping records and returning a partial total.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A memory repair that silently ignores bad rows may run successfully while producing the wrong business result.

        Words you will see

        Diagnostic
        An explanation of a failure that helps locate it.
        Partial result
        An answer based on only part of the intended data.
        Read-ahead
        Requesting input beyond the record currently needed.

        Locate the error without retaining the report

        The fixture converts 7, then fails on bad at row 2. A conversion-specific try/except adds row context and chains the original error with from error. The caller catches the error for a deterministic display, then reads the still-open source.

        The next line is 9, proving that this particular parser stopped before consuming it. That is stronger boundary evidence than only checking the exception text. It still is not a memory benchmark, and does not prove behavior for arbitrary input sizes.

        Choose the failure policy before changing it

        A fail-fast financial total may be safer than a partial answer. A data-cleaning preview might deliberately skip invalid records, but should return counts and bounded diagnostics so the caller knows the result is incomplete.

        Keeping every bad row in an error list creates another unbounded output. Keep only a limited sample plus a count if that is the policy. Never catch every exception and return zero: it hides programming errors, resource failures and data corruption behind a plausible numeric result.

        The original example, step by step

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

        1. except ValueError as error:

          Catch only the integer conversion failure at this boundary.

        2. raise ValueError(f'Invalid integer at row {number}') from error

          Add the row while preserving the original cause.

        3. parse_total(source)

          Borrow the source and stop when row 2 cannot be parsed.

        4. print(next(source).strip())

          The unconsumed third row remains available to the owner.

        For bounded cardinality, an in-memory aggregation is simple. For unbounded distinct groups, use partitioning, external sorting or a database. Choose fail-fast versus a bounded error report explicitly; never silently skip corrupt records.

        Predict before you run

        Which line remains after the error?

        Keep error context and the remaining cursorPYTHON 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 invalid boundary.

        Try: Use 'bad\n8\n9\n'.

        The error names row 1 and the next line displayed is 8.

        Demonstrate the narrower contract.

        Try: Use '7\n-2\n9\n' and print(parse_total(source)) instead of the try and later next call.

        The result is 14; integer parsing alone does not reject negative minutes.

        Before you move on

        Does this parse_total enforce the earlier nonnegative-minutes contract?

        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 isolates conversion diagnostics and accepts negative integers. To implement the minutes contract, add a separate negative-value check with row context before updating total.

        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.