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, ' ') will evaluate the given function until the sentinel value, ' ', is found. This must be used carefully: if the sentinel is not found, it can continue reading zero-length strings forever.

Providing a callable function to iter() can be a bit challenging because the function we provide must maintain some state internally. This is generally looked at as undesirable in functional programs. However, hidden state is a feature of an open file, for example, each read() or readline() function advances the internal state to the next character or next line. 

Another example of explicit iteration is the way that a mutable collection object's pop() method makes a stateful change to a collection object. The following is an example of using the pop() method:

>>> tail = iter([1, 2, 3, None, 4, 5, 6].pop, None)
>>> list(tail)
[6, 5, 4]

The tail variable was set to an iterator over the list [1, 2, 3, None, 4, 5, 6] that will be traversed by the pop() function. The default behavior of pop() is pop(-1), that is, the elements are popped in the reverse order. This makes a stateful change to the list object: each time pop() is called, the item is removed, mutating the list. When the sentinel  value is found, the iterator stops returning values. If the sentinel is not found, this will break with an IndexError exception. 

This kind of internal state management is something we'd like to avoid. Consequently, we won't try to contrive a use for this feature.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset