Iteration
Sentinel Iteration
The two-argument form turns a polling callable into an iterator. The empty string stops the loop without appearing in the result.
Source
chunks = iter(["py", "thon", ""])
def read_chunk():
return next(chunks)
print(list(iter(read_chunk, "")))Output
['py', 'thon']The equivalent manual loop needs an explicit read, comparison, and break. Use this shape when the stop condition is more complicated than a single sentinel value.
Source
chunks = iter(["py", "thon", ""])
word = ""
while True:
chunk = next(chunks)
if chunk == "":
break
word += chunk
print(word)Output
pythonNotes
- The callable passed to
iter(callable, sentinel)must take no arguments. - The sentinel stops iteration and is not yielded.
- When the loop needs richer branching, an explicit
whileloop may be clearer.
See also
- related: Iterators
- next depth: While Loops
- prerequisite: Break and Continue
Run the complete example
Expected output
['py', 'thon']
python
Execution time appears here after you run the example.