The iter() function with a sentinel value
The built-in iter()
function creates an iterator over an object of one of the collection classes. The list
, dict
, and set
classes all work with the iter()
function to provide an iterator
object for the items in the underlying collection. In most cases, we'll allow the for
statement to do this implicitly. In a few cases, however, we need to create an iterator explicitly. One example of this is to separate the head from the tail of a collection.Â
Other uses include building iterators to consume the values created by a callable object (for example, a function) until a sentinel value is found. This feature is sometimes used with the read()
function of a file to consume items until some end-of-line or end-of-file sentinel value is found. An expression such as iter(file.read, '\n')
will evaluate the given function until the sentinel value, '\n'
, is found. This must be used carefully: if the sentinel is not found, it can continue reading zero-length strings...