Practical technology learning
Python Generators: Predict What Remains After One Pass
A generator can look like a collection when a for loop reads it, yet behave very differently when the same object is used again. This small exercise makes consumption visible before you depend on a second pass through a larger dataset.
Set up a tiny, repeatable source
Use only synthetic integers. Create g = (n * n for n in range(4)). Before running anything else, write the four values you expect the generator to yield. Keep the object in g so every later operation refers to the same iterator.
This exercise supports Python programming practice, including learners comparing Python courses in Jaipur. It is a proposed lab, not a report of a delivered class or student result.
Predict each consuming operation
Call next(g) once. The expected result is 0. Now evaluate list(g): it collects the remaining values, so the expected result is [1, 4, 9]. Evaluate list(g) again and expect an empty list. The generator has already reached its end; converting it again does not restart its expression.
Compare an iterable with its iterator
A list such as [0, 1, 4, 9] can be iterated repeatedly because each ordinary for loop asks it for a fresh iterator. A generator object is itself an iterator and keeps its current position. Giving a generator a new variable name creates another reference to that same object, not a fresh traversal.
Try three deliberate variations
- Create a new generator expression before each traversal and compare the results.
- Materialise the values once in a list when repeat reads and the memory cost are acceptable.
- Write a function containing yield, then call the function again to obtain a new generator object.
Decide who owns consumption
Imagine a preview function reads the first item before a reporting function receives the iterator. Document that side effect: the report will start with the next item unless the interface makes a different arrangement. A helpful review question is whether a helper promises to inspect a source or to consume it.
Do not claim that generators always make an application faster. They can avoid materialising every value at once, but runtime and memory depend on the workload and on what later code stores.
Keep a useful learning record
Save the exact sequence of operations, your predictions and the observed outputs. Add one sentence explaining why a second list conversion is empty. That evidence is more useful than a screenshot showing only the first successful loop. Explore the related Python learning path for broader foundations and confirm current course details with Mango Engineers.