The iterator abstraction

Iterator objects are created implicitly when we use an iterable container with a for statement. We rarely expect to see the iterator object itself. For the most part, it will be a concealed portion of the implementation of the for statement. The few times we do care about the iterator object, we rarely want to extend or revise the class definition.

We can expose the implicit iterators that Python uses through the iter() function. We can interact with an iterator in the following way:

>>> x = [1, 2, 3] 
>>> iter(x) 
<list_iterator object at 0x1006e3c50> 
>>> x_iter = iter(x) 
>>> next(x_iter) 
1 
>>> next(x_iter) 
2 
>>> next(x_iter) 
3 
>>> next(x_iter) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
StopIteration 
>>> isinstance(x_iter, collections.abc.Iterator) 
True 

In the preceding code, we created an iterator over a list object, assigning it to the x_iter variable. The next() function will step through the values in that iterator. This shows how iterator objects are stateful, and the next() function both returns a value and updates the internal state.

The final isinstance() expression confirmed that this iterator object is an instance of collections.abc.Iterator.

Most of the time, we'll work with iterators that have been created by the collection classes themselves; however, when we branch out and build our own collection classes or extend a collection class, we may also need to build a unique iterator. We'll look at iterators in Chapter 7, Creating Containers and Collections.

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

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