Python › Iterators & the Iterator Protocol

How does Python's iter() function work with a sentinel value as a second argument?

Intermediate

Answer

iter(callable, sentinel) repeatedly calls callable with no arguments and yields each result until the result equals sentinel, at which point iteration stops. This is useful for turning polling-style APIs (like reading fixed-size chunks or reading until a marker) into a clean iterator.
with open('data.bin', 'rb') as f:
    for chunk in iter(lambda: f.read(1024), b''):
        process(chunk)
Real-world example A file-reading loop uses iter(f.read_chunk, '') to process a stream in fixed-size blocks until an empty read signals end-of-file.

Common follow-ups: What other APIs commonly use the sentinel pattern?;How does this compare to a while-loop with a manual read?