Iterator Pattern

noun

say it: “IT-uh-ray-ter PAT-urn” /ˈɪtəreɪtər ˈpætərn/

A design pattern in which a collection hands out an object that walks its items one at a time and keeps its place, so callers never need to know how the items are stored.

What is the Iterator pattern?

The Iterator pattern has a collection hand out an iterator: an object that keeps its place and answers "is there another?" and "what is it?". Callers walk the items without knowing whether they're stored as a list, in zones or in pages from a server. Every for-each loop uses one.

class Route:
    def __init__(self, zones):
        self._zones = zones

    def __iter__(self):  # hands out the stops, one at a time
        for zone in self._zones:
            yield from zone


for stop in Route([["Maple St", "Oak Ave"], ["Pine Rd"]]):
    print(stop)  # Maple St, then Oak Ave, then Pine Rd

In a sentence

  • “Thanks to the Iterator pattern, the driver's app didn't change when routes were split into zones.”
  • “Every for-each loop you write uses the Iterator pattern behind the scenes.”

Level: Journeyman · More OOP terms at this level

Updated