10 Iterators and generators

 

Have you ever noticed that many Python objects know how to behave inside of a for loop? That’s not an accident. Iteration is so useful, and so common, that Python makes it easy for an object to be iterable. All it has to do is implement a handful of behaviors, known collectively as "the iterator protocol."

In this chapter, we’ll explore that protocol, and how we can use it to create iterable objects. We’ll do this in three ways:

  1. We’ll create our own iterators via Python classes, directly implementing the protocol ourselves.
  2. We’ll create "generators," objects that implement the protocol, based on something that looks very similar to a function. Not surprisingly, these are known as "generator functions."
  3. We can also create generators using "generator expressions," which look quite a bit like list comprehensions. We’ll cover all three of these techniques in this chapter.

Even newcomers to Python know that if I want to iterate over the characters in a string, I can write:

for i in 'abcd':
    print(i)   #1

This feels natural, and that’s the point. What if I just want to execute a chunk of code five times? Can I iterate over the integer 5? Many newcomers to Python assume that the answer is "yes," and write the following:

for i in 5:   #1
    print(i)

The above code produces an error:

TypeError: 'int' object is not iterable

10.1  MyEnumerate

10.1.1  Solution

10.1.2  Discussion

10.1.3  Beyond the exercise

10.2  Circle

10.2.1  Solution

10.2.2  Discussion

10.2.3  Beyond the exercise

10.3  All lines, all files

10.3.1  Solution

10.3.2  Discussion

10.3.3  Beyond the exercise

10.4  Elapsed since

10.4.1  Solution

10.4.2  Discussion

10.4.3  Beyond the exercise

sitemap