5.4 The iter() function with a sentinel value
The built-in iter()
function creates an iterator over an object of a collection class. 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 of the iter()
function 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()
method 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...