Iteration

Sentinel Iteration

iter(callable, sentinel) repeats calls until a marker value appears.

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']
iter(read, '')valuevaluevalue''sentinel · stop
`iter(callable, sentinel)` calls the callable repeatedly, stopping when it returns the sentinel.

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

python

Notes

See also

Run the complete example

Example code

Expected output

['py', 'thon']
python

Execution time appears here after you run the example.