Compare a Python iterator with a materialised list
Predict and run a Python iterator exercise. Compare repeated traversal, materialising remaining values and generator timing without unsupported memory or speed claims.
Run through a collection once, then try to run through it again. With a list, that usually feels unremarkable. With an iterator you have already consumed, the second pass may produce nothing. That difference matters when a small Python program first prints a preview and then tries to calculate a total from the same stream.
This local exercise compares an iterator with a materialised list using three invented order amounts. There are no files, external services or customer records. Predict each output before running the code, then explain the result from the object's state rather than calling one choice universally better.
Separate the collection from the cursor
The Python tutorial's iterator section explains that a for loop obtains an iterator with iter(), and that next() advances it until StopIteration signals exhaustion. A list is an iterable collection; an iterator carries a position in a traversal. You can obtain a fresh iterator from the same unchanged list for another pass. Calling iter() on an existing iterator does not rewind its position.
Our example deliberately builds the iterator from a list so the distinction is visible. This is not a memory-saving benchmark: the source list already exists. Materialising means collecting the remaining values into a list now. It changes what you retain for later use, but cannot recreate values that have already been consumed.
Predict the first and second pass
Save the following as iterator_practice.py and run it with your installed Python 3 interpreter. These are the complete inputs for this block. Each print consumes the object passed to list() if it is an iterator; printing a list built earlier simply displays that stored list.
amounts = [12, 18, 25]
stream = iter(amounts)
print(next(stream))
print(list(stream))
print(list(stream))
print(amounts)
print(sum(amounts))
The expected lines are 12, then [18, 25], then [], then [12, 18, 25], then 55. The first next() consumed 12. The first list(stream) collected what remained; the second found an exhausted iterator. None of those steps removed items from amounts. The distinction is between consuming a traversal and deleting from the underlying collection.
Materialise before you need repeated access
Now start a fresh block. If you want both a preview and a total from a one-pass source, collecting its output once can be a reasonable choice when the result is suitably bounded. Keep the collected result and use it for both operations. Do not repeatedly call list() on the original stream and expect identical data.
stream = iter([12, 18, 25])
saved = list(stream)
print(saved[:2])
print(sum(saved))
print(list(stream))
print(sum(saved))
Expect [12, 18], 55, [] and 55. The saved list remains available for repeated iteration and indexing. The original stream is exhausted. If you collect only after calling next(stream), the saved list starts with the remaining values instead; that can silently change a calculation if you forgot about the preview.
Notice when the computation happens
A generator makes the timing easier to observe. This new, independent block prints a marker just before producing each value. The markers belong to the exercise, not to a recommended logging design. Run it from the beginning and retain the order of the lines.
def doubled(values):
for value in values:
print("produce", value)
yield value * 2
stream = doubled([2, 4])
print("ready")
print(next(stream))
print("collect")
print(list(stream))
The sequence is ready, produce 2, 4, collect, produce 4 and [8]. Creating this generator did not execute its body to completion. Advancing it ran enough code to yield a value; collecting the remainder resumed it. In real code, deferred work can also raise an error during consumption. A successful generator construction therefore does not prove that every later value can be produced.
Choose from the work you actually need
| Requirement | Question to ask |
|---|---|
| One sequential pass | Can the consumer process each value without retaining all earlier values? |
| Repeated passes or indexing | Is a bounded stored collection appropriate, or can the source safely be read again? |
| Preview followed by processing | Will the preview consume values needed by the later step? |
A generator need not retain every produced result at once, while list() retains the results it collects. The actual memory footprint also depends on the source, generator state, objects and consumer. The iterator in our first block still refers to a list already in memory. Do not use this demonstration to claim a particular saving, speed advantage or capacity for a production dataset.
Write a useful diagnosis
For a fictional bug report, describe the first operation as “preview consumed one value” and the later observation as “total used only the remaining values”. Include the exact inputs and output. That gives a reviewer a reproducible explanation. “Python lost an order” would suggest a different problem and conceal the cursor state that actually matters here.
Keep a note of whether a source can be replayed. A fresh generator over the same fixed inputs can provide a new traversal; a remote stream, file position or changing query may need different handling. This exercise tests none of those dependencies. Re-reading real data also needs appropriate access and a clear account of changes between reads.
Common questions
Does list(stream) reset stream?
No. It consumes the remaining values and returns a new list. It does not rewind the iterator.
Does an empty second result mean the source list is empty?
No. Inspect the source and traversal separately, as the first block demonstrates.
Should I always convert an iterator to a list?
No. Decide from bounded size, repeat access and the consumer's needs. Test the real workload before making performance claims.
Explore Python web development learning or discuss a demo. Bring your predicted and actual output, and ask for feedback on the reasoning behind each line.
Admissions
Request a call back
Tell us which course you are interested in and the counselling desk will call you about fees, batches and a free demo class.
18008913982 (toll free) · +91 9899-355-335
[email protected]
Open the enquiry form in a separate window ↗
Your enquiry goes to Coding Bytes through ViaCRM so the counselling team can respond. Please share only the details needed for your question, not passwords, payment details or sensitive documents. Privacy & enquiries · Before enrolling
