Python › Iterators & the Iterator Protocol
How does Python's iter() function work with a sentinel value as a second argument?
IntermediateAnswer
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.