Generate values only when needed
Understand iteration, exhaustion and the memory cost of materialising.
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: 12 minutes; optional deep dive: 9 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.
- Use iter and next
- Write a generator
- Explain single-pass consumption
Iterable versus iterator
An iterable can supply values for iteration. An iterator is the advancing cursor that remembers which value comes next.
Understand first
Understand why a second pass over a list works but a second pass over the same cursor may be empty.
Words you will see
- Iterable
- An object accepted by iter(), such as a list.
- Iterator
- An object advanced by next(); iter(iterator) returns that same iterator.
- Exhaustion
- The state after an iterator has no next value; next raises StopIteration unless given a default.
Advance one shared cursor
iter([10, 20]) creates a cursor before 10. next(cursor) returns 10 and advances past it. list(cursor) then consumes the remainder, so it displays [20], not [10, 20].
The second list(cursor) asks that same exhausted cursor for more and gets []. Converting a cursor to a list does not rewind it. Creating a new iterator from the original list would start a fresh traversal.
Choose a useful exhaustion rule
next(cursor, 'done') returns the default after exhaustion rather than raising StopIteration. Without that second argument, the exception is the normal signal used by for loops to stop.
A list is reusable data, but its iterator is a one-way traversal. An empty list supplies a cursor that is exhausted immediately. Do not use truthiness of the cursor to ask whether it has another item.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
cursor = iter([10, 20])Create one position-tracking iterator over two values.
print(next(cursor))Consume 10 and print it.
print(list(cursor))First occurrence consumes 20; the second occurrence finds no values.
An iterable can provide an iterator. An iterator advances through values and remembers its position. next consumes one value; exhaustion raises StopIteration unless a default is supplied.
Conceptual cursor positions for the original example; consuming a cursor does not delete list entries.
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Readyiter([10, 20]) → cursor before 10.
- One requestnext(cursor) returns 10 → cursor before 20.
- Consume the restlist(cursor) returns [20] → cursor exhausted.
- No rewindlist(cursor) again returns []; create a new iterator for another traversal.
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 both values directly.
Try: Insert print(next(cursor)) after the first next print.
The next output is 20 and both later list conversions are empty.
Use an exhaustion default.
Try: Append print(next(cursor, 'done')).
It prints done instead of raising StopIteration.
Before you move on
After c = iter([7, 8, 9]) and next(c), what are list(c) and then next(c, None)?
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 list is [8, 9]. That consumes the remaining values, so next(c, None) then returns None.
Yield pauses a function
A generator function pauses at yield and resumes on the next request, keeping its local state between requests.
Understand first
Produce squares one at a time when downstream code may stop early, rather than constructing every square in advance.
Words you will see
- yield
- Give one value to the caller and suspend this function's execution.
- Generator function
- A function whose body contains yield; calling it creates a generator iterator.
- Materialise
- Consume produced values into a stored collection such as a list.
Separate creation from execution
Calling squares(4) creates a generator without running the loop body yet. list requests successive values. range(4) supplies 0, 1, 2, 3, and yield supplies 0, 1, 4, 9.
After each yield, execution pauses before continuing the loop. Reaching the end exhausts this generator. A new squares(4) call creates a new traversal; reusing the old generator does not restart it.
Do not hide the allocation at the caller
The generator does not retain a growing list of past squares. However, the example's list call explicitly retains all four values for display. The complete display therefore does allocate a result list.
A zero or negative limit makes range empty, so list(squares(limit)) is []. The example assumes integer limits. yield is different from return: return would end the generator on its first loop iteration.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def squares(limit):Define the producer; the body runs when its generator is advanced.
for value in range(limit):Visit integers starting at zero and stopping before limit.
yield value * valueProvide a square and suspend, rather than finish the call.
print(list(squares(4)))Request and store all four generated values for display.
A generator function yields a value and suspends its state until the next request. It can stream a large sequence without storing every result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Advance by hand.
Try: Replace the print with g = squares(4); print(next(g)); print(next(g)).
The outputs are 0 and 1, with later squares still unrequested.
Test exhaustion.
Try: Store g = squares(2); print(list(g)); print(list(g)).
The outputs are [0, 1] then [], because one generator is single-pass.
Before you move on
What does list(squares(1)) contain, and what does list(squares(0)) contain?
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
They contain [0] and [] respectively. range stops before its limit, so 1 includes zero but 0 includes no values.
When laziness helps
Laziness helps when a consumer can use and discard each item. It does not supply random access or make a consumed cursor reusable.
Understand first
Choose between a fresh generator, a retained list and an incremental total based on what the next step actually needs.
Words you will see
- Consumer
- Code that requests values from an iterable.
- Pipeline
- Stages where one stage's output becomes the next stage's input.
- Single-pass
- Values are consumed once through this iterator.
A total consumes the stream
positive_values yields only the values greater than zero. sum(stream) consumes 2 and 3 and returns 5 without storing an output list. list(stream) afterwards is empty because sum already drove it to exhaustion.
The original values list still exists and is unchanged. Creating positive_values(values) again would supply another traversal over that list. You cannot restart the same generator by calling iter(stream).
Choose storage only when needed
If callers need indexing, length or repeated traversal of results, list(positive_values(values)) can be the right choice. The result list costs space proportional to the number of retained values.
The generator itself keeps a reference to values while suspended. It avoids a second output collection but does not erase the existing source list. For n inputs, filtering and summing visit O(n) items under ordinary arithmetic assumptions.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if value > 0:Reject -1 and 0, retaining only 2 and 3.
print(sum(stream))Request all remaining yielded values and accumulate 5.
print(list(stream))The already-consumed stream has no remaining values.
print(values)Filtering did not change the input list.
Use generators for pipelines where each value can be processed and discarded. If you need random access, length, or repeated traversals, retaining a collection or recreating the iterator may be appropriate.
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.
Retain the filtered results.
Try: Change stream = positive_values(values) to stream = list(positive_values(values)).
sum no longer consumes a cursor stored in stream; the second print is [2, 3].
Test no matches.
Try: Use values = [-1, 0].
The total is 0, the consumed stream is empty, and the original list remains [-1, 0].
Before you move on
How can you obtain both a total and a reusable list of positives?
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
Materialise the positives once into a list, then sum that list and reuse it. Or recreate the generator from a reusable source; a one-shot source cannot be replayed automatically.
Where this idea earns its place
A stream is useful when each value can be processed and discarded, such as a log parser or a sequence of computed measurements. The important contract is whether values can be replayed. A list normally supplies a fresh iterator for each traversal; an iterator itself remembers progress and may only be consumed once.
Follow the mechanism step by step
iter obtains an iterator and next advances it. A generator function begins executing when values are requested, pauses at yield and retains local state until resumed or closed. Reaching the end produces StopIteration to its consumer. list(generator) and sum(generator) both consume that stream.
Work through a concrete application
Trace an iterator through next, then list, then list again. Record exactly which values each consumer receives. Next write a generator that filters even values and compare it with a list-producing function. Decide whether callers need indexing, length or repeated traversal before choosing a lazy return type.
Failure cases and misleading shortcuts
Validation or logging can accidentally exhaust the stream before the real operation. Delayed execution also means an exception can arise after a surrounding function has returned. A generator holding a resource open across yields needs deliberate closing behaviour; do not rely on an eventual collector to finish an abandoned pipeline.
Cost, ownership and alternatives
A generator retains its frame and referenced inputs, so lazy is not synonymous with zero memory. Materialising downstream removes much of the storage benefit. Sorting a complete dataset needs retained data, and duplicating consumers with tee can require a large buffer when they advance at different rates.
Verify the contract
Test empty, partially consumed and exhausted iterators, as well as exceptions after several yields. Test whether a second traversal is supported or intentionally empty. For a resource-owning generator, verify cleanup on normal completion, explicit close and failure rather than testing only the final values.
Transfer question: A report needs both a total and details from a non-repeatable stream. What are the choices?
Compute both in one traversal when possible, store only the bounded detail required, or deliberately materialise within a known size limit. Recreating the iterator is valid only when its source is repeatable and has acceptable cost and consistency semantics.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Yield even values
Generate even values below 8 without building a list inside the function.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Consume only the remainder
Turn the current position of an iterator into a list without inventing a restart.
The contract
- Implement remaining(cursor) for a finite iterator of integers; return a list of values not yet consumed.
- Consume cursor through exhaustion; preserve order and duplicates. Already exhausted cursors return [].
- Do not mutate any underlying source list. Do not call iter on a remembered external source to restart it.
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.
- ordinary
r = remaining(iter([2, 1])); assert type(r) is list and r == [2, 1]
- empty
r = remaining(iter([])); assert type(r) is list and r == []
- partly consumed
c = iter([7, 8, 9]); next(c); r = remaining(c); assert type(r) is list and r == [8, 9]
- exhaustion
c = iter([4]); a = remaining(c); b = remaining(c); assert type(a) is list and type(b) is list and a == [4] and b == []
- duplicates
r = remaining(iter([2, 2, -1])); assert type(r) is list and r == [2, 2, -1]
- source preservation
p = [3, 1, 3]; c = iter(p); next(c); r = remaining(c); assert type(r) is list and r == [1, 3] and p == [3, 1, 3] and next(c, None) is None
Does consuming the iterator remove values from its list?
No. It advances the cursor, not the list contents. Materialising k remaining entries costs O(k) time and O(k) list space.
Yield even values
Generate even integers below a limit without constructing an output list.
The contract
- Implement evens(limit) as a generator function for integer limits.
- Yield 0, 2, ... strictly below limit. Zero or negative limits yield nothing.
- Return a generator iterator, not a list or range. Do not allocate a result list or use external resources.
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.
- ordinary generator
import types g = evens(8); assert isinstance(g, types.GeneratorType) and list(g) == [0, 2, 4, 6]
- zero
import types g = evens(0); assert isinstance(g, types.GeneratorType) and list(g) == []
- negative
import types g = evens(-3); assert isinstance(g, types.GeneratorType) and list(g) == []
- exclusive boundary
import types g = evens(2); assert isinstance(g, types.GeneratorType) and list(g) == [0]
- odd boundary
import types g = evens(5); assert isinstance(g, types.GeneratorType) and list(g) == [0, 2, 4]
- one-shot cursor
import types g = evens(4); assert isinstance(g, types.GeneratorType) and next(g) == 0 and list(g) == [2] and list(g) == []
What memory benefit disappears in list(evens(limit))?
The consumer stores all yielded values. The producer uses O(1) loop state under fixed-size arithmetic; producing k values takes O(k) time, and materialising them adds O(k) result space.
Transfer: remember a running total
Unlike independent evens, each yielded value now depends on all earlier input.
The contract
- Implement running_totals(values) as a generator over a finite iterable of integers, including one-shot iterators.
- Yield a total after each input; [] yields nothing, negatives and duplicates count. Consume each input once.
- Do not pre-read the source at generator creation or mutate a source list. No output list or external resources.
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.
- ordinary
import types g = running_totals([2, 3, 1]); assert isinstance(g, types.GeneratorType) and list(g) == [2, 5, 6]
- empty
import types g = running_totals([]); assert isinstance(g, types.GeneratorType) and list(g) == []
- repeated and negative
import types g = running_totals([2, 2, -5]); assert isinstance(g, types.GeneratorType) and list(g) == [2, 4, -1]
- singleton zero
import types g = running_totals([0]); assert isinstance(g, types.GeneratorType) and list(g) == [0]
- source preservation
import types p = [4, 1, 4]; g = running_totals(p); assert isinstance(g, types.GeneratorType) and list(g) == [4, 5, 9] and p == [4, 1, 4]
- lazy single pass
import types events = [] def source(): for v in [3, 4]: events.append(v) yield v g = running_totals(source()); assert isinstance(g, types.GeneratorType) and events == [] assert next(g) == 3 and events == [3] assert list(g) == [7] and events == [3, 4] and list(g) == []
What new state is needed compared with evens?
A total must survive each suspension. One pass takes O(n) arithmetic updates with O(1) local state, excluding integer growth and any memory held by the source or consumer.
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 milestoneLazy does not mean free
A suspended generator keeps its local bindings alive, including references to large objects, until it finishes or closes.
Understand first
Avoid assuming that delaying output automatically releases a large input collection.
Words you will see
- Retained reference
- A connection that keeps an object reachable and potentially alive.
- close()
- End a generator's suspended execution and trigger its cleanup.
- Aliasing
- Different names refer to the same mutable object.
Observe the retained source
read_first(source) does not copy source. On its first next, it yields source[0] and pauses. The caller then sets data[1] to 99. On resumption the generator reads source[1] from that same list and yields 99.
Laziness means the second read happens later, not that the source was frozen at generator creation. A tuple snapshot could give stable flat values, but allocating it would cost time and space up front.
Account for both state and storage
This generator holds source across its pause. Its own small local state does not imply the reachable list is small. A downstream list or sorted call also materialises results and changes memory costs.
Use streaming sources where appropriate and define who may mutate them. A closed or exhausted generator cannot be reused. Do not promise prompt release of every external object merely because one generator reference was deleted.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
yield source[0]Read 10 now and pause with source retained.
data[1] = 99Mutate the same list before the next request.
print(next(g))The first call reads index zero; the second resumes and reads the updated index one.
g.close()Close the suspended generator explicitly.
A generator retains local state and anything it references. Calling list(generator) still allocates all results. Some operations, such as sorting the complete input, require materialisation.
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.
Compare rebinding.
Try: Replace data[1] = 99 with data = [1, 99].
The second result is 20 because source still names the original list.
Make a snapshot.
Try: Replace g = read_first(data) with g = read_first(tuple(data)).
The later list mutation does not alter the tuple; the second result is 20.
Before you move on
Would changing data to a new list after the first next alter the retained 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. data = [1, 2] rebinds the caller's name, while source still refers to the old list. Mutating the old list and rebinding the name are different.
Resource lifetime matters
A generator can hold a resource while paused. Give ownership and cleanup an explicit rule, especially when a consumer stops early.
Understand first
Learn cleanup without pretending browser Python opens real production files or manages operating-system connections.
Words you will see
- finally
- A cleanup block run when control leaves its try block, including generator closing.
- Resource lifetime
- The interval during which something such as an open handle is held.
- Early exit
- A consumer stops before asking for every available value.
Pause inside a protected region
The sample uses a local events list as a conceptual resource log, not a real file. On first next, records appends 'open', enters try, yields 1 and pauses. No 'close' has happened yet.
g.close() resumes termination at the paused yield. The finally block appends 'close'. This is explicit cleanup when the consumer stops before the second value, not evidence that a browser has acquired a real OS handle.
Define the owner of real resources
In a local Python file pipeline, a with open block inside a generator may keep the file open across yields. A consumer's break does not by itself guarantee every arbitrary iterator is closed. Make closing part of the owner contract.
Here there are no files, network calls or child processes. Browser-compatible code can demonstrate Python's finally and close mechanism, while real filesystem or network lifecycle tests belong in an appropriate local lab. Closing a never-started generator does not execute body code that was never entered.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
events.append('open')Log entry into this simulated resource scope on first advancement.
yield 1Pause before the second yield, keeping the try block active.
g.close()Terminate the started generator so its finally block runs.
events.append('close')Record cleanup once control leaves the protected region.
A generator that yields while holding an open file can keep that resource alive across suspensions. Design explicit ownership and closing behaviour rather than relying on garbage collection.
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.
Exhaust normally.
Try: Replace print(next(g)) with print(list(g)).
It prints [1, 2]; the first events print already includes open and close.
Close before starting.
Try: Replace print(next(g)) with g.close().
Both events prints are []; the generator body never entered the simulated resource scope.
Before you move on
If the consumer exhausts list(records()) instead of closing early, will finally run?
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
Yes, normal exhaustion leaves the try block and runs finally too. It yields both 1 and 2 first; explicit close is important for the early-stop case.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.