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

Scenario: the second report is unexpectedly empty

A generator feeds a total calculation and then a detail report. The total is correct, but the detail report is empty. Restarting the process does not help; each run repeats the same first-success/second-empty pattern.

IntermediateScenario 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 who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

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

Actual runtime and local-lab boundaries

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

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

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

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 generator feeds a total calculation and then a detail report. The total is correct, but the detail report is empty. Restarting the process does not help; each run repeats the same first-success/second-empty pattern.

Observed evidence

  • The same iterator object is passed to both consumers.
  • The first consumer traverses it completely.
  • Replacing it with a list makes both consumers see values.

Investigation sequence

  1. Distinguish a reusable iterable from a single-pass iterator.
  2. Check whether logging or validation consumed the iterator first.
  3. Choose regeneration, materialisation or a one-pass combined report according to cost.

Challenge the repair

  • Write a test showing that one iterator is exhausted but a fresh generator is not.
  • How would you create both reports in one pass over a non-repeatable stream?
01

Read the incident, not just the error

An iterator remembers progress. After a consumer reaches the end, a second consumer sees no remaining values unless a fresh source is supplied.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The incident's correct total and empty detail report are consistent with sharing one exhausted iterator, not with missing original data.

Words you will see

Iterable
An object from which iter() can obtain an iterator.
Iterator
An object that supplies the next value and remembers its current position.
Exhausted
Having reached the end; later next calls continue to signal StopIteration.

Reproduce the first-success, second-empty pattern

A generator expression creates a single iterator over 2, 4 and 6. sum reads all three to produce 12. list then asks that same object for remaining values and finds none. Restarting this program repeats the consumption pattern; it does not fix ownership.

The empty detail is evidence about the stream's position, not proof that a query returned zero records. A logger, preview or validation pass may also have consumed it. Track which component requested each value before blaming the producer.

Know which object is reusable

A list is iterable and can create a fresh iterator for each traversal. An iterator's iter call returns that iterator itself, without resetting it. The list alternative retains all values, while a generator can supply them lazily.

If both reports need all values, choose an explicit policy: regenerate from a safe factory, materialise a bounded snapshot, or compute both in one pass. Each changes cost or ownership. None can magically replay a one-time source at no cost.

The original example, step by step

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

  1. values = (number for number in [2, 4, 6])

    Create one generator iterator, not a reusable list of results.

  2. print(iter(values) is values)

    iter returns this same iterator; it does not rewind.

  3. print(sum(values))

    Consume every yielded number to form 12.

  4. print(list(values))

    Ask only for remaining values, which are now absent.

A generator feeds a total calculation and then a detail report. The total is correct, but the detail report is empty. Restarting the process does not help; each run repeats the same first-success/second-empty pattern.

Conceptual cursor ownership, not a runtime trace

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

  1. CreateOne iterator has cursor before 2.
  2. Totalsum requests 2, 4, 6, then the end.
  3. Detaillist asks the same exhausted cursor and gets no values.
  4. ChooseSupply a fresh cursor, retain a snapshot, or build both results in one pass.
Predict before you run

What does list(values) show after sum?

Reproduce the exhausted second reportPYTHON 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 only one item first.

Try: Replace print(sum(values)) with print(next(values)).

The first print becomes 2 and list shows [4, 6], exposing partial consumption.

Use reusable stored data.

Try: Replace the generator expression with [2, 4, 6].

iter(values) is values becomes False and the detail list still contains all three numbers.

Before you move on

Would assigning second = values before sum create an independent detail 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

No. Both names would refer to the same iterator and position. A second name does not create a second traversal or cache values.

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

Investigate before changing code

A diagnostic observer can change a single-pass source by reading it. Test consumption directly instead of judging correctness only from printed reports.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Adding debug output can make a lazy pipeline fail even though no values are explicitly deleted from a collection.

Words you will see

Consumer
Code that requests values from an iterator.
Sentinel
A distinct marker used to represent no next value.
StopIteration
The signal that an iterator has no next item.

Make the observer effect reproducible

The preview consumes 3. sum therefore sees only 5 and 7, producing 12 rather than 15. Calling next with a default after exhaustion returns the marker instead of raising StopIteration. Neither call puts values back.

A preview based on list(source) would consume even more. Log metadata about the producer without pulling values when possible. If a preview is required, include its consumption in the API or deliberately preserve that value in a new chain.

Test the boundary that matters

A tracking iterator can record each yielded value, forbid a second traversal, or raise if a consumer reads past a prefix. Assert the remaining cursor as well as result type and value. These tests reject a helper that materialises everything before returning a seemingly correct prefix.

Restoring one preview item with itertools.chain costs one retained reference but does not make the whole source repeatable. Copying iterator names is still sharing; materialising a snapshot costs storage proportional to its retained values. Choose the smallest honest boundary.

The original example, step by step

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

  1. print('preview', next(source))

    The observer advances the cursor before the total runs.

  2. print('remaining total', sum(source))

    Add only 5 and 7; the previously displayed 3 is gone from this cursor.

  3. marker = object()

    Create a unique absence marker, distinct from any normal input.

  4. print(next(source, marker) is marker)

    Observe exhaustion without confusing it with a valid numeric zero.

Distinguish a reusable iterable from a single-pass iterator. Check whether logging or validation consumed the iterator first. Choose regeneration, materialisation or a one-pass combined report according to cost.

Predict before you run

Which numbers contribute to the remaining total?

A preview consumes a valuePYTHON 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 observer.

Try: Delete the preview print.

The remaining total becomes 15, which reveals that debugging had changed the input position.

Test an empty iterator safely.

Try: Use iter([]) and replace the preview with next(source, 'empty').

The preview displays empty, sum is 0 and the final sentinel check is True.

Before you move on

If zero is a valid next value, can next(source, 0) distinguish that value from the end?

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. Both would produce zero. A unique object sentinel allows an identity check that does not confuse valid data with exhaustion.

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

A repair you can explain

A factory can provide a fresh iterator for each report when the input is cheap, safe and meaningful to regenerate.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The preserved repair makes independent traversals explicit instead of relying on a consumed generator to rewind.

Words you will see

Factory
A callable that creates a new source when called.
yield from
Syntax that forwards values from another iterable into a generator.
Repeatability
Whether another traversal can produce suitable data again.

Explain the two calls in the original source

Calling values() creates a generator; its body runs as values are requested. yield from forwards 2, 4 and 6. sum consumes the first generator completely. The second values() call creates a different generator, so list sees all three values.

This works because the sample's literal data is repeatable and has no external side effects. Returning the same old generator from a function named factory would not satisfy the freshness promise. Test identity and factory call counts rather than trusting its name.

Do not confuse freshness with a snapshot

A new database query could return changed records or repeat expensive work. A live stream may not be replayable at all. In those cases, one bounded materialisation can provide a consistent snapshot at the cost of retaining every value.

For a non-repeatable source, a combined one-pass report is another repair. A total alone needs little state, but returning all detail rows necessarily retains them. State that output cost instead of advertising the combined report as constant-memory.

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 values():

    Define a generator factory rather than one shared generator.

  2. yield from [2, 4, 6]

    Forward three supplied values each time a fresh generator is consumed.

  3. print(sum(values()))

    Create and exhaust the first generator for the total.

  4. print(list(values()))

    Create another generator for the detail report.

Each call returns a fresh generator. This works when input can be regenerated; it is not automatically suitable for a one-time network stream or expensive external query.

Predict before you run

Why does the second report contain all values?

Recreate the stream deliberatelyPYTHON 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.

Reintroduce the bug.

Try: Assign source = values() and pass source to both consumers.

The total stays 12 but the detail becomes [], because both use one cursor.

Change the repeatable fixture.

Try: Use [2, 4, 6, 8] inside values.

Both fresh reports see the change: total 20 and four detail values.

Before you move on

What if values() returns a module-level generator instead of creating one?

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

Then repeated calls share that generator's position. The total can exhaust it and the detail can be empty again. A fresh callable name is not evidence of fresh underlying state.

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 first-success, second-empty sequence

Keep one generator object, feed it to the total calculation, and then pass that same object to the detail report. The first consumer gets all the values and the second gets none. Save that sequence as the regression reproduction, including the identity of the shared iterator. Restarting repeats the failure because each run makes the same ownership mistake; there is no stale disk state to clear and no nondeterministic scheduler needed to explain it.

Compare an iterator with a reusable iterable under controlled conditions. A list can create fresh independent iterators, while a generator object is itself a cursor with a current position. Calling iter on an existing generator does not rewind it. Inspect whether diagnostic logging, validation, list conversion, or a preliminary count consumed values before the intended report. An observer that reads the stream can change the very state being investigated.

Trace suspension, consumption and exhaustion

Each next request resumes the generator until it yields or completes. sum repeatedly requests values until completion; later consumers see StopIteration immediately. The reference values function yields 2, 4, and 6. Calling values separately for sum and list creates two generator objects, so the outputs are 12 and a three-item detail list. The repair works because the function can regenerate the same inexpensive deterministic data without external side effects.

A generator retains its suspended local state and anything reachable from it. Laziness avoids holding every yielded result only if downstream consumers also avoid materializing them. It does not provide free repeated traversal, and it can prolong a file or connection lifetime across yields. Distinguish an exhausted cursor from a closed external resource and from a source that returned zero rows; these cases may display the same empty output but require different repairs.

Choose regeneration, retention or a combined pass

Regenerate when the source is repeatable, affordable, and stable under the required consistency contract. A second database query can see changed rows, and repeating a network stream can incur cost or repeat side effects. Materializing once provides repeated access to the same snapshot at O(n) retained result space. For a small bounded dataset that trade is often clearer than a complicated lazy design, provided the bound is stated.

For a non-repeatable stream, compute both reports during one traversal or spool a snapshot under an explicit storage policy. A total can be updated while detail rows are emitted to an owned output stream, but failure may leave partial output that needs a completeness marker or replacement strategy. itertools.tee can duplicate traversal interfaces, yet its buffer grows when consumers advance at different rates; it cannot promise constant-memory duplication for arbitrary consumption schedules.

Verify traversal and cleanup contracts

Test the same iterator twice to demonstrate exhaustion, then test two fresh generators to demonstrate independent traversal. Include empty input, a single item, and early termination. Use a source that records each request to verify that a combined-pass implementation reads each record once. If output must reflect one snapshot, change the underlying source between hypothetical reads and confirm the chosen strategy does not accidentally combine inconsistent versions.

Add a failure after several yields and verify that the source and output resources are closed according to ownership. Do not catch that failure and present the partial detail file as a complete report. Document which component may retain values and why: a bounded accumulator, an explicit materialized snapshot, or external storage. This makes resource costs and consistency visible to callers rather than hiding them behind a return type that merely says iterable.

Transfer question: You must produce a total and a detail export from a one-time stream, with limited memory. What design avoids exhaustion without an unbounded tee buffer?

Traverse once, increment the total for each validated record, and write its detail representation to an owned staging output. Keep only the current record and bounded formatting buffers. Publish the completed output and total only after the traversal succeeds; remove or clearly mark an incomplete staging artifact if parsing or writing fails. If the final format requires the total before its first detail row, use a format supporting a summary trailer or spool details to bounded external storage before assembly. Test early source failure and output failure, because a one-pass happy result alone does not establish cleanup.

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

Write a test showing that one iterator is exhausted but a fresh generator is not. 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

Build both reports from one iterator

Consume one single-pass integer iterator and return matching total and detail.

The contract

  • Input is a finite iterator of built-in ints. Return a built-in tuple (total, rows), where total is a built-in int and rows a new built-in list in arrival order.
  • Use one traversal; preserve duplicates and zero. Empty input returns (0, []). The input is consumed to exhaustion, not rewound, replaced or closed.
  • Keep each original yielded value in rows. Output detail retains one reference per item; this is not a constant-storage report.
Build both reports from one iteratorPYTHON 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. One source, two complete results
    s = iter([2, 4, 6])
    r = combined_report(s)
    assert type(r) is tuple and len(r) == 2 and type(r[0]) is int and type(r[1]) is list and r == (12, [2, 4, 6]) and list(s) == []
  2. Empty result shape
    s = iter([])
    r = combined_report(s)
    assert type(r) is tuple and len(r) == 2 and type(r[0]) is int and type(r[1]) is list and r == (0, []) and list(s) == []
  3. Duplicates, negatives and zero
    s = iter([0, -2, -2, 4])
    r = combined_report(s)
    assert type(r) is tuple and len(r) == 2 and type(r[0]) is int and type(r[1]) is list and r == (0, [0, -2, -2, 4]) and list(s) == []
  4. Already advanced source
    s = iter([9, 3, 5])
    assert next(s) == 9
    r = combined_report(s)
    assert type(r) is tuple and len(r) == 2 and type(r[0]) is int and type(r[1]) is list and r == (8, [3, 5]) and list(s) == []
  5. Single traversal enforced
    class Once:
        def __init__(self):
            self.data = iter([3, 7]); self.calls = 0; self.seen = []
        def __iter__(self):
            self.calls += 1
            assert self.calls == 1, 'second traversal'
            return self
        def __next__(self):
            value = next(self.data)
            self.seen.append(value)
            return value
    s = Once()
    r = combined_report(s)
    assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (10, [3, 7]) and s.seen == [3, 7] and next(s, None) is None
  6. Fresh result list and untouched owner
    owner = [1000, 2000]
    s = iter(owner)
    r = combined_report(s)
    assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (3000, [1000, 2000]) and r[1] is not owner and all(a is b for a, b in zip(r[1], owner)) and list(s) == []
    r[1].append(9)
    assert owner == [1000, 2000]
    Could both results be computed with no retained detail?

    Not if a full detail list is required. The loop is linear in yielded items, plus numeric addition costs, and rows retains n references. Total-and-count alone could avoid that list.

    GUIDED PRACTICE

    Make the factory boundary explicit

    Use a supplied factory for two deliberate, independent observations.

    The contract

    • Input is a zero-argument callable returning a fresh finite integer iterator per call. Call it exactly twice: once for a total, then once for detail.
    • Return a built-in tuple (total, rows) with built-in int total and new built-in list rows. Consume both returned iterators to exhaustion without closing them.
    • The two sources may contain different data: total belongs to the first, detail to the second. Preserve detail order and duplicates; do not claim a consistent snapshot.
    Make the factory boundary explicitPYTHON 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 fresh sources
      sources = []
      def factory():
          s = iter([2, 4, 6]); sources.append(s); return s
      r = fresh_reports(factory)
      assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (12, [2, 4, 6]) and len(sources) == 2 and sources[0] is not sources[1] and all(next(s, None) is None for s in sources)
    2. Empty factory data
      sources = []
      def factory():
          s = iter([]); sources.append(s); return s
      r = fresh_reports(factory)
      assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (0, []) and len(sources) == 2 and all(next(s, None) is None for s in sources)
    3. Changed data is not a snapshot
      sources = []
      def factory():
          s = iter([1, 2] if not sources else [8, 8, 0]); sources.append(s); return s
      r = fresh_reports(factory)
      assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (3, [8, 8, 0]) and len(sources) == 2 and all(next(s, None) is None for s in sources)
    4. Negative and zero values
      sources = []
      def factory():
          s = iter([-3, 0, -3]); sources.append(s); return s
      r = fresh_reports(factory)
      assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (-6, [-3, 0, -3]) and len(sources) == 2 and all(next(s, None) is None for s in sources)
    5. First completes before second opens
      events = []
      sources = []
      def rows():
          events.append('start'); yield 5
          events.append('end')
      def factory():
          events.append('open'); s = rows(); sources.append(s); return s
      r = fresh_reports(factory)
      assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (5, [5]) and events == ['open', 'start', 'end', 'open', 'start', 'end'] and len(sources) == 2 and all(s.gi_frame is None for s in sources)
    6. New detail list shares yielded integers
      owner = [1000, 2000]
      sources = []
      def factory():
          s = iter(owner); sources.append(s); return s
      r = fresh_reports(factory)
      assert type(r) is tuple and type(r[0]) is int and type(r[1]) is list and r == (3000, [1000, 2000]) and r[1] is not owner and all(a is b for a, b in zip(r[1], owner)) and owner == [1000, 2000] and len(sources) == 2 and all(next(s, None) is None for s in sources)
      What cost and consistency trade-off does this API expose?

      It performs two source traversals and retains the second detail list. The total and detail may differ if the factory observes changing data. Use a one-pass combined report for one consistent observation instead.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: preserve a live cursor for the next page

      A report now requests only a batch from a non-repeatable stream. Do not regenerate, snapshot everything or read an extra item.

      The contract

      • Borrow an iterator of arbitrary objects and an integer limit. Return a new built-in list containing at most limit next references, in order with duplicates.
      • Leave unrequested values on the same iterator, without rewind or closing. Zero performs no next call; negative limit raises ValueError before any next call.
      • If the source ends early, return the shorter batch. Do not prefetch a limit-plus-one value or clone the yielded objects.
      Transfer: preserve a live cursor for the next pagePYTHON 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 and remainder identity
        a, b, c = object(), object(), object()
        s = iter([a, b, c])
        r = next_batch(s, 2)
        assert type(r) is list and len(r) == 2 and r[0] is a and r[1] is b and next(s) is c
      2. Empty source
        s = iter([])
        r = next_batch(s, 4)
        assert type(r) is list and r == [] and next(s, None) is None
      3. Zero cannot touch source
        seen = []
        def rows():
            seen.append('read'); yield 7
        s = rows()
        r = next_batch(s, 0)
        assert type(r) is list and r == [] and seen == [] and s.gi_frame is not None and next(s) == 7
      4. Repeated reference and short source
        a = {}
        s = iter([a, a])
        r = next_batch(s, 5)
        assert type(r) is list and len(r) == 2 and r[0] is a and r[1] is a and next(s, None) is None
      5. Exact next-call budget
        class Cursor:
            def __init__(self): self.calls = 0
            def __iter__(self): return self
            def __next__(self):
                self.calls += 1
                assert self.calls <= 2, 'prefetched third item'
                return self.calls
        s = Cursor()
        r = next_batch(s, 2)
        assert type(r) is list and r == [1, 2] and s.calls == 2
      6. Invalid limit preserves source
        seen = []
        def rows():
            seen.append('read'); yield 8
        s = rows()
        try:
            next_batch(s, -1)
        except ValueError:
            assert seen == [] and s.gi_frame is not None and next(s) == 8
        else:
            raise AssertionError('negative limit accepted')
        Why does list(source)[:limit] violate this contract even if the returned batch looks right?

        It drains the source before slicing, so later pages disappear and storage grows with all remaining input. Pulling k requested items uses O(k) output references and leaves the rest owned by the caller's live cursor.

        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

        Materialising once creates a reusable snapshot of the yielded references. It trades storage for consistent repeated access, without deep-copying mutable values.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Two reports that must use exactly the same observations may need a snapshot rather than two fresh reads from a changing producer.

        Words you will see

        Snapshot
        A stored collection of values observed during one traversal.
        Shallow copy
        A new outer container whose elements can still be shared objects.
        One pass
        A single traversal of a source, without replay or restarting.

        Combine the reports at one consumption boundary

        The loop reads each value once, adds it to total, and appends it to rows. The total and rows therefore use the same observations. After the loop the original iterator is exhausted, which is an intentional part of this consuming contract.

        The rows list stores n references for n observations. It preserves order and duplicates. If the elements were mutable records, another owner could still edit those records; a new list does not freeze their contents.

        Compare against regeneration

        A repeatable cheap source can use two independent passes and avoid storing detail if it is written elsewhere. A changing or one-time source cannot assume those passes match. The combined report avoids replay but cannot avoid the storage required by its returned detail list.

        If only total and count are required, keep those two aggregates and no rows. If rows must remain accessible, bound their number or use an explicit storage adapter outside this local example. No choice makes unlimited retained detail free.

        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 value in source:

          Read each value exactly once from the borrowed iterator.

        2. total += value

          Update the numeric report at the same boundary.

        3. rows.append(value)

          Retain the detail reference in its original order.

        4. print(list(source))

          Confirm the original cursor is intentionally exhausted.

        An iterator remembers its position and stays exhausted after StopIteration. list(iterator), sum(iterator) and many debugging operations consume it. A lazy pipeline can therefore change behaviour if an observer reads from the stream.

        Predict before you run

        What extra storage does the detail report require?

        Make two results from one traversalPYTHON 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 output requirement.

        Try: Replace rows.append(value) with count += 1, initialise count = 0, and print total and count.

        It reports 12 and 3 without retaining the detail list.

        Test duplicates.

        Try: Use [2, 2, 6] as the input.

        The total is 10 and rows contains both 2 values; no deduplication occurred.

        Before you move on

        If the requested output changes to total and count only, should rows still be retained?

        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. Increment a counter alongside total. Removing the detail requirement removes the need to retain all n values, though integer sizes can still grow.

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

        Alternatives and operational trade-offs

        itertools.tee creates independently advancing consumers by buffering values they have not all reached. It does not give free, constant-storage replay.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A tempting repair can postpone the memory problem when one report finishes long before the other starts.

        Words you will see

        tee
        A standard-library tool that splits one iterable into independently advancing iterators.
        Lag
        How far one consumer is behind another.
        Buffer
        Retained values needed to serve a slower consumer later.

        Follow the faster and slower consumer

        fast reads 2 and 4 before slow reads 2. tee must make 2 available to slow even though the original source has advanced. The final lists show each branch's remaining values: fast has 6; slow has 4 and 6.

        This demonstrates independent cursors, not the internal buffer layout or its exact byte size. If fast drains an n-value stream while slow has not started, shared state can retain about n yielded values for slow. The cost follows lag, not just the number of branch objects.

        Choose a simpler policy where possible

        Use explicit materialisation for a small bounded reusable snapshot, fresh factories for genuinely replayable data, or one pass for combined aggregates. tee is useful when consumers advance together and buffering is acceptable.

        Do not continue reading the original iterator separately after splitting it, because those reads bypass tee's shared path. tee is not a durable broker or a thread-safe multi-consumer delivery system. A bounded preview with strict no-read-ahead semantics should pull only its requested number of values.

        The original example, step by step

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

        1. fast, slow = tee(iter([2, 4, 6]))

          Create two branches sharing one underlying consumption path.

        2. print(next(fast), next(fast))

          Advance fast twice; slow still needs those values.

        3. print(next(slow))

          Slow receives the earlier 2, not the original source's current position.

        4. print(list(slow))

          The slower branch can still read its remaining 4 and 6.

        Materialising once trades memory for repeated access. Re-running a query can return different data or repeat side effects. itertools.tee buffers values when consumers advance at different rates, so it is not free constant-memory duplication.

        Predict before you run

        What does slow read first after fast has read two items?

        Observe independently advancing tee branchesPYTHON 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.

        Keep the branches in step.

        Try: Read one fast value, then one slow value, before reading their lists.

        Both remaining lists contain [4, 6]; the branches can advance together.

        Compare aliasing instead.

        Try: Replace tee with source = iter([2, 4, 6]); fast = slow = source.

        After fast reads 2 and 4, slow reads 6, and both final lists are empty.

        Before you move on

        If total drains fast before detail starts slow, has tee eliminated storage proportional to the report size?

        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 lag can grow to the whole input, so tee may retain values for the detail consumer. An explicit snapshot makes that cost easier to see.

        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.