Programming with Python · free preview

Iteration Protocols and Functional Tools

Implement the iterator protocol on your own classes, walk sequences in parallel with zip, and map and filter data with the functional built-ins.

1. Overview

Overview

2. Making Your Own Iterable

Making Your Own Iterable

3. Walking Sequences Together

Walking Sequences Together

4. map and filter

map and filter

5. Asking Questions of a Sequence

Asking Questions of a Sequence

6. Days and Readings

Days and Readings

7. A Countdown Iterable

A Countdown Iterable

8. The else on a loop and the walrus operator

The else on a loop and the walrus operator

9. Recognize iterator exhaustion

For it = iter(Squares(4)), list(it) returns [1, 4, 9]. What does list(it) return on the second call?

10. Tracing Countdown through the iterator protocol

Create one Countdown(3), then call next(iter(values)), next(values), read values.current, and call list(values) twice more. Predict the internal current value and the five printed lines.

Example. Tracing Countdown through the iterator protocol

Problem. Create one Countdown(3), then call next(iter(values)), next(values), read values.current, and call list(values) twice more. Predict the internal current value and the five printed lines.

Correct solution.

python
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

values = Countdown(3)
print(next(iter(values)))
print(next(values))
print(values.current)
print(list(values))
print(list(values))

关键提醒。

Input is one object, values = Countdown(3), with initial state current == 3.

Trace:

  1. iter(values) returns the same object because __iter__ returns self.
  2. The first next lowers current from 3 to 2 and returns current + 1, which is 3.
  3. The second next lowers current from 2 to 1 and returns 2.
  4. Printing values.current shows 1, confirming that state lives on the object.
  5. The first list consumes the remaining item: current goes from 1 to 0, 1 is returned, then the next call raises StopIteration.
  6. The final list calls __next__ while current is 0, so it immediately raises StopIteration and returns [].

Expected output:

Output

3
2
1
[1]
[]

11. Retrieval practice

For first = Countdown(3), predict the exact output of: print(list(first)); print(list(first)); print(list(Countdown(3))). Then explain in terms of __iter__, __next__, and StopIteration why the second call differs.

python
first = Countdown(3)
print(list(first))
print(list(first))
print(list(Countdown(3)))

12. Mastery check

Implement Squares(limit) so list(Squares(4)) is [1, 4, 9]. Then use zip on days = ["mon", "tue"] and readings = [36.6, 37.0, 38.4]. Give the class, the exact list(zip(days, readings)) output, and say which reading is dropped.

python
class Squares:
    # implement __init__, __iter__, and __next__

days = ["mon", "tue"]
readings = [36.6, 37.0, 38.4]
print(list(Squares(4)))
print(list(zip(days, readings)))

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free