Summary

Summarize the concept explored in this chapter regarding the Iterator pattern in Python.

We'll cover the following

Recall

This chapter looked at a design pattern that seems ubiquitous in Python, the iterator. The Python iterator concept is a foundation of the language and is used widely. In this chapter we examined a number of aspects:

  • Design patterns are good ideas we see repeated in software implementations, designs, and architectures. A good design pattern has a name, and a context where it’s usable. Because it’s only a pattern, not reusable code, the implementation details will vary each time the pattern is followed.
  • The Iterator protocol is one of the most powerful design patterns because it provides a consistent way to work with data collections. We can view strings, tuples, lists, sets, and even files as iterable collections. A mapping contains a number of iterable collections including the keys, the values, and the items (key and value pairs.)
  • List, set, and dictionary comprehensions are short, pithy summaries of how to create a new collection from an existing collection. They involve a source iterable, an optional filter, and a final expression to define the objects in the new collection.
  • Generator functions build on other patterns. They let us define iterable objects that have map and filter capabilities.

Synopsis

In this chapter, we learned that design patterns are useful abstractions that provide best-practice solutions for common programming problems. We covered our first design pattern, the iterator, as well as numerous ways that Python uses and abuses this pattern for its own nefarious purposes. The original iterator pattern is extremely object-oriented, but it is also rather ugly and verbose to code around. However, Python’s built-in syntax abstracts the ugliness away, leaving us with a clean interface to these object-oriented constructs.

Comprehensions and generator expressions can combine container construction with iteration in a single line. Generator functions can be constructed using the yield syntax.

Get hands-on with 1200+ tech skills courses.