{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7a46ccb3",
   "metadata": {},
   "source": [
    "# Iterators"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbf21536",
   "metadata": {},
   "source": [
    "Every `for` loop you have written so far relies on an **iterator**. Looping over a list, the characters of a string, the keys of a dictionary, or the lines of a file all work the same way: *Python asks the object for one value at a time until there are no values left*. This shared mechanism is called the **iterator protocol**, and it is why a single `for` statement works with so many different types.\n",
    "\n",
    "Iterators matter because data often comes in larger amounts than memory can comfortably hold, or arrives as a stream with no fixed end. A log file with millions of lines, a stream of sensor readings, or the rows of a large CSV file can be processed one item at a time, without first loading everything into a list. An iterator that computes each value only when requested is called **lazy**.\n",
    "\n",
    "You use iterators all the time, often without noticing. `enumerate()`, `zip()`, `map()`, `filter()`, file objects, `csv.reader()`, and most of the `itertools` module return lazy iterators. Others, such as `range()` and `dict.items()`, are lazy iterables: they don't store a full list of values, and each `for` loop gets a fresh iterator from them.\n",
    "\n",
    "Writing an iterator class takes some boilerplate. {doc}`Generators <1102-generators>` shows how a generator function produces the same behavior with far less code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 1\n",
    "```"
   ],
   "id": "contents"
  },
  {
   "cell_type": "markdown",
   "id": "8d8ba868",
   "metadata": {},
   "source": [
    "## The Iterator Protocol\n",
    "\n",
    "A protocol is a contract about behavior, not a type you have to inherit from. In computing, a protocol is a set of rules that both sides agree to follow, like HTTP between a browser and a server. In Python, it means: \"if your object provides these specific methods, everything that expects this behavior will work with it.\"\n",
    "\n",
    "The protocol has two parts. An object you can loop over is an **iterable**: its type defines `__iter__()`. Stepping through the values takes a second object, an **iterator**, whose type defines both `__iter__()` and `__next__()`.\n",
    "\n",
    "An iterator is the object that does the work of a loop: it hands out values one at a time and remembers where it is. Each role signs a different part of the contract:\n",
    "\n",
    "| Role | Must have | Promise | Example |\n",
    "|---|---|---|---|\n",
    "| **Iterable** | `__iter__()` | returns an iterator | `list`, `str`, `dict` |\n",
    "| **Iterator** | `__iter__()` and `__next__()` | `__next__` gives the next item or raises `StopIteration`; `__iter__` returns self | `list_iterator`, map objects, generators |\n",
    "\n",
    "So, `list` signs only the first contract. Its one job is to hand over an object that signs the second. A `for` loop uses the list's iterable contract once to get an iterator, then the iterator contract repeatedly:\n",
    "\n",
    "```python\n",
    "for x in nums:\n",
    "#   it = nums.__iter__()         <-- iterable contract (list)\n",
    "#   x = it.__next__()  ...       <-- iterator contract (list_iterator)\n",
    "```\n",
    "\n",
    "A list is an iterable, not an iterator, so to step through it by hand you call `iter()` to get a separate iterator object.\n",
    "\n",
    "<!-- Its `__iter__()` returns the iterator itself, so an iterator is also iterable. -->\n",
    "<!-- File objects and generators are iterators.  -->"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-8d8ba868",
   "metadata": {},
   "source": [
    "```{index} iterator protocol, iterable, StopIteration\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8400d872",
   "metadata": {},
   "outputs": [],
   "source": [
    "# iter() creates an iterator from any iterable\n",
    "nums = [10, 20, 30]\n",
    "it = iter(nums)\n",
    "print(type(it))           # <class 'list_iterator'>\n",
    "\n",
    "# next() fetches values one at a time\n",
    "print(next(it))           # 10\n",
    "print(next(it))           # 20\n",
    "print(next(it))           # 30\n",
    "\n",
    "# Calling next() past the end raises StopIteration\n",
    "try:\n",
    "    print(next(it))\n",
    "except StopIteration:\n",
    "    print(\"StopIteration raised: sequence exhausted\")\n",
    "\n",
    "# A second iterator over the same list starts at the beginning\n",
    "it2 = iter(nums)\n",
    "print(next(it2))          # 10: it2 has its own position\n",
    "print(iter(it2) is it2)   # True: iter() on an iterator returns the same object\n",
    "print(next(iter(it2)))    # 20: so it keeps its place instead of starting over"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-two-iters",
   "metadata": {},
   "source": [
    "Each `iter()` call on the list creates a new iterator with its own position, so `it2` starts at `10` even though the first iterator, `it`, is used up. Calling `iter()` on an iterator does not start over: it returns the same object, which keeps its place. The list stores the data; each iterator is a separate cursor with its own position in the list."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1633909",
   "metadata": {},
   "source": [
    "### What a `for` Loop Does\n",
    "\n",
    "Every `for` loop runs the iterator protocol for you. When Python reaches `for item in my_list:`, it calls `iter(my_list)` once to get an iterator, then calls `next()` on that iterator before each pass through the loop body. When `next()` raises `StopIteration`, Python catches the exception and ends the loop quietly, so you never see it.\n",
    "\n",
    "The two loops below do the same work. The first is the loop you write; the second spells out the `iter()` and `next()` calls Python makes for you:"
   ]
  },
  {
   "cell_type": "code",
   "id": "aedf1898",
   "metadata": {},
   "source": [
    "my_list = [10, 20, 30]\n",
    "\n",
    "# The loop you write\n",
    "for item in my_list:\n",
    "    print(item, end=' ')\n",
    "print()\n",
    "\n",
    "# What Python does for you\n",
    "it = iter(my_list)\n",
    "while True:\n",
    "    try:\n",
    "        item = next(it)\n",
    "    except StopIteration:\n",
    "        break   # the normal end of the loop, not an error\n",
    "    print(item, end=' ')\n",
    "print()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "1e611d9d",
   "metadata": {},
   "source": [
    "This is why any object that follows the protocol works in a `for` loop and in functions such as `list()`, `sum()`, and `max()`: all of them use the same `iter()` and `next()` steps. It also explains what happens when you loop over an iterator instead of a list: the loop's `iter()` call returns the same iterator, so the loop picks up wherever earlier `next()` calls stopped."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-it-step-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Step Through an Iterator\n",
    "#   1. Create an iterator from `colors` with `iter()`.\n",
    "#   2. Print the first two colors with two `next()` calls.\n",
    "#   3. Loop over the same iterator with a `for` loop and print what is left.\n",
    "#      The loop continues from where `next()` stopped.\n",
    "#   4. Call `next()` once more inside `try`/`except StopIteration` and print\n",
    "#      \"No more colors\".\n",
    "#   Print exactly:\n",
    "#   red\n",
    "#   green\n",
    "#   blue\n",
    "#   No more colors\n",
    "colors = ['red', 'green', 'blue']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ch11-it-step-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "red\n",
      "green\n",
      "blue\n",
      "No more colors\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "colors = ['red', 'green', 'blue']\n",
    "it = iter(colors)\n",
    "\n",
    "print(next(it))   # red\n",
    "print(next(it))   # green\n",
    "\n",
    "for color in it:  # picks up at 'blue'\n",
    "    print(color)\n",
    "\n",
    "try:\n",
    "    next(it)\n",
    "except StopIteration:\n",
    "    print(\"No more colors\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd237fa7",
   "metadata": {},
   "source": [
    "## Built-in Lazy Iterators\n",
    "\n",
    "Python has many built-in **lazy iterators**: they produce values on demand rather than building a list first, which keeps memory usage low for large inputs.\n",
    "\n",
    "\"Iterator\" and \"lazy\" answer different questions. *Iterator* describes how an object hands out values: one per `next()` call, remembering its place. *Lazy* describes when those values exist. The iterator from `iter(my_list)` steps through values the list already stores, so nothing is saved by waiting. A lazy iterator such as `map(len, fruits)` stores no results at all; it computes each one only when `next()` is called. That is why `map()` over a million items costs almost no memory until you consume it. `range()` is lazy too, but it is an iterable rather than an iterator: each loop gets a fresh iterator from it.\n",
    "\n",
    "| | Object | Iterator? | Where the values come from | Lazy? |\n",
    "| - |---|---|---|---|\n",
    "| 1 | `[10, 20, 30]` | No (an iterable) | Stored in the list | No |\n",
    "| 2 | `iter([10, 20, 30])` | Yes | Read from the list, which already stores them | No |\n",
    "| 3 | `map(len, fruits)`, `zip(a, b)`, `enumerate(seq)`, `filter(f, seq)` | Yes | Computed on each `next()` call | Yes |\n",
    "| 4 | `range(1_000_000_000)` | No (an iterable) | Computed as a loop steps through it | Yes (a lazy iterable) |\n",
    "\n",
    "`reversed(seq)` also returns an iterator, but it belongs in row 2, not row 3: it reads the values the sequence already stores, starting from the end. It also needs a sequence, something with `len()` and indexing, so `reversed(map(len, fruits))` raises `TypeError`, while the four lazy iterators accept any iterable.\n",
    "\n",
    "The built-in lazy iterators used in this section:\n",
    "\n",
    "| Iterator | What it produces |\n",
    "|---|---|\n",
    "| `enumerate(seq)` | `(index, value)` pairs |\n",
    "| `zip(a, b)` | `(a_item, b_item)` pairs, stops at the shorter |\n",
    "| `map(f, seq)` | `f(item)` for each item |\n",
    "| `filter(f, seq)` | items where `f(item)` is truthy |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-fd237fa7",
   "metadata": {},
   "source": [
    "```{index} lazy iterator, enumerate(), zip(), map(), filter()\n",
    "```\n",
    "\n",
    "```{index} reversed()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c380cfd4",
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = ['apple', 'banana', 'cherry']\n",
    "\n",
    "# enumerate: index + value pairs\n",
    "for i, fruit in enumerate(fruits, start=1):\n",
    "    print(f\"{i}. {fruit}\")\n",
    "\n",
    "# zip: pair two sequences together\n",
    "prices = [1.20, 0.50, 2.00]\n",
    "for fruit, price in zip(fruits, prices):\n",
    "    print(f\"{fruit}: ${price:.2f}\")\n",
    "\n",
    "# map and filter return iterators (wrap in list() to inspect)\n",
    "lengths = list(map(len, fruits))           # [5, 6, 6]\n",
    "long_ones = list(filter(lambda f: len(f) > 5, fruits))  # ['banana', 'cherry']\n",
    "print(lengths)\n",
    "print(long_ones)\n",
    "\n",
    "# reversed: an iterator, but not lazy (reads the stored list backward)\n",
    "for fruit in reversed(fruits):\n",
    "    print(fruit, end=' ')\n",
    "print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-lazy-show",
   "metadata": {},
   "source": [
    "These loops use each result right away, so they would print the same output if the built-ins returned lists. To see when the work actually happens, give `map()` a function that reports each call:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-it-lazy-map",
   "metadata": {},
   "outputs": [],
   "source": [
    "def shout(word):\n",
    "    print(f\"  computing {word!r}\")\n",
    "    return word.upper()\n",
    "\n",
    "loud = map(shout, fruits)     # nothing printed: no work done yet\n",
    "print(\"map object created\")\n",
    "print(next(loud))             # only now: computing 'apple', then APPLE\n",
    "print(next(loud))             # computing 'banana', then BANANA"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-lazy-note",
   "metadata": {},
   "source": [
    "Each value is computed only when `next()` asks for it, and `'cherry'` is never computed because nothing asked for it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03e9c443",
   "metadata": {},
   "source": [
    "### Built-in Iterators Are Single-Use\n",
    "\n",
    "In {doc}`Functional Programming <../10-functional/1001-func-prog>` you saw that `map()` and `filter()` are lazy and can be used only once. `enumerate()`, `zip()`, and `reversed()` behave the same way: all five return iterators, and an iterator can be used only once. The trap is reusing the result, because the second pass silently gets nothing."
   ]
  },
  {
   "cell_type": "code",
   "id": "b1a8c981",
   "metadata": {},
   "source": [
    "fruits = ['apple', 'banana', 'cherry']\n",
    "lengths = map(len, fruits)\n",
    "\n",
    "print(sum(lengths))                # 17\n",
    "print(sum(lengths))                # 0, not 17: lengths is already used up\n",
    "\n",
    "lengths = list(map(len, fruits))   # need the values twice? store them in a list\n",
    "print(sum(lengths), max(lengths))  # 17 6"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-single-fix",
   "metadata": {},
   "source": [
    "If you need the values more than once, convert the iterator to a list, or call the built-in again to get a fresh iterator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-it-lazy-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Combine Lazy Iterators\n",
    "#   1. Use enumerate() and zip() together to print a numbered line for\n",
    "#      each student and score, starting at 1, e.g. \"1. Ana: 88\".\n",
    "#   2. Use filter() with a lambda to keep the scores of 80 or more,\n",
    "#      and print them as a list.\n",
    "#   3. Use map() to add 5 bonus points to every score, and print the\n",
    "#      result as a list.\n",
    "#   Print exactly:\n",
    "#   1. Ana: 88\n",
    "#   2. Ben: 72\n",
    "#   3. Cy: 95\n",
    "#   [88, 95]\n",
    "#   [93, 77, 100]\n",
    "names = ['Ana', 'Ben', 'Cy']\n",
    "scores = [88, 72, 95]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ch11-it-lazy-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1. Ana: 88\n",
      "2. Ben: 72\n",
      "3. Cy: 95\n",
      "[88, 95]\n",
      "[93, 77, 100]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "names = ['Ana', 'Ben', 'Cy']\n",
    "scores = [88, 72, 95]\n",
    "\n",
    "for i, (name, score) in enumerate(zip(names, scores), start=1):\n",
    "    print(f\"{i}. {name}: {score}\")\n",
    "\n",
    "print(list(filter(lambda s: s >= 80, scores)))   # [88, 95]\n",
    "print(list(map(lambda s: s + 5, scores)))        # [93, 77, 100]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c9cad21",
   "metadata": {},
   "source": [
    "## Custom Iterator Classes\n",
    "\n",
    "The built-ins cover common patterns, but sometimes you need your own stepping rule or want to hand out values from your own data structure one at a time. Then you write a class that follows the iterator protocol. Python recognizes such a class by two special methods, the same kind of double-underscore methods as `__init__()` and `__str__()` in {doc}`OOP Design and Methods <../09-oop/0901-oop-design>`:\n",
    "\n",
    "- **`__iter__(self)`** is what `iter(obj)` calls. An iterator returns `self`, because it is already the object that hands out values. A `for` loop always calls `iter()` first, so without this method the loop would fail.\n",
    "- **`__next__(self)`** is what `next(obj)` calls. It returns the next value, or raises `StopIteration` when there are no more.\n",
    "\n",
    "The object also has to remember where it is between calls. That position lives in an attribute set by `__init__()` and updated by every `__next__()` call."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-2c9cad21",
   "metadata": {},
   "source": [
    "```{index} custom iterator, next method (__next__), iter method (__iter__)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-countdown-lead",
   "metadata": {},
   "source": [
    "`Countdown` counts down from a starting number. Its position is `self.current`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cac09288",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Countdown:\n",
    "    \"\"\"Counts down from `start` to 1, then raises StopIteration.\"\"\"\n",
    "\n",
    "    def __init__(self, start):\n",
    "        self.current = start\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self          # the iterator IS the object\n",
    "\n",
    "    def __next__(self):\n",
    "        if self.current <= 0:\n",
    "            raise StopIteration\n",
    "        value = self.current\n",
    "        self.current -= 1\n",
    "        return value\n",
    "\n",
    "\n",
    "# Works in a for loop\n",
    "for n in Countdown(5):\n",
    "    print(n, end=' ')\n",
    "print()   # 5 4 3 2 1\n",
    "\n",
    "# Also works with list(), sum(), max(), etc.\n",
    "print(list(Countdown(4)))    # [4, 3, 2, 1]\n",
    "print(sum(Countdown(10)))    # 55"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-countdown-steps",
   "metadata": {},
   "source": [
    "Each call to `__next__()` follows the same four steps:\n",
    "\n",
    "1. If no values are left, raise `StopIteration`.\n",
    "2. Save the current value to return.\n",
    "3. Move the position forward (in `Countdown`, down by one).\n",
    "4. Return the saved value.\n",
    "\n",
    "Because `Countdown` follows the protocol, it works anywhere an iterable does: in a `for` loop and in `list()`, `sum()`, and `max()`.\n",
    "\n",
    "Each of those lines creates a `Countdown` object even though none is assigned to a name. `Countdown(5)` builds a new instance and runs `__init__()`; the `for` loop then calls `iter()` on it, gets the same object back from `__iter__()`, and calls `next()` until `StopIteration`. When the loop ends, nothing refers to the object, so Python frees it. `list(Countdown(4))` and `sum(Countdown(10))` each build their own instance in the same way."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-numberrange-lead",
   "metadata": {},
   "source": [
    "The sample `NumberRange` below rebuilds the built-in `range()` as a class. The end test depends on the direction of `step`: counting up stops at or above `stop`, counting down stops at or below it. A `step` of 0 would never reach `stop`, so the class rejects it in `__init__()` with a `ValueError` rather than producing an iterator that never ends."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cfeae5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "class NumberRange:\n",
    "    \"\"\"Iterates from `start` to `stop` (exclusive) by `step`.\"\"\"\n",
    "\n",
    "    def __init__(self, start, stop, step=1):\n",
    "        if step == 0:\n",
    "            raise ValueError(\"step must not be zero\")   # would never reach stop\n",
    "        self.current = start\n",
    "        self.stop = stop\n",
    "        self.step = step\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    def __next__(self):\n",
    "        if (self.step > 0 and self.current >= self.stop) or \\\n",
    "           (self.step < 0 and self.current <= self.stop):\n",
    "            raise StopIteration\n",
    "        value = self.current\n",
    "        self.current += self.step\n",
    "        return value\n",
    "\n",
    "\n",
    "print(list(NumberRange(1, 10, 2)))    # [1, 3, 5, 7, 9]\n",
    "print(list(NumberRange(10, 0, -3)))   # [10, 7, 4, 1]\n",
    "\n",
    "try:\n",
    "    NumberRange(1, 3, 0)\n",
    "except ValueError as e:\n",
    "    print(\"ValueError:\", e)           # ValueError: step must not be zero"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65cc31a2",
   "metadata": {},
   "source": [
    "### Skipping Values\n",
    "\n",
    "`__next__()` does not have to return the very next item of its data. It can keep looking until it finds a value worth returning. The `Positives` class below stores an iterator over its input rather than a copy of it, so it reads one value at a time, like the built-in lazy iterators. Its `__next__()` loops over that iterator, returns as soon as a value qualifies, and raises `StopIteration` only after the input runs out. Because the stored iterator keeps its position, each call's loop resumes where the last one stopped:"
   ]
  },
  {
   "cell_type": "code",
   "id": "3131442a",
   "metadata": {},
   "source": [
    "class Positives:\n",
    "    \"\"\"Iterates over only the positive numbers in `values`, one at a time.\"\"\"\n",
    "\n",
    "    def __init__(self, values):\n",
    "        self.source = iter(values)    # an iterator, not a copy of the data\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    def __next__(self):\n",
    "        for value in self.source:     # resumes where the last call stopped\n",
    "            if value > 0:\n",
    "                return value          # found one: hand it back and pause\n",
    "        raise StopIteration           # input exhausted: nothing left\n",
    "\n",
    "print(list(Positives([4, -1, 7, 0, 3, -2, 8])))   # [4, 7, 3, 8]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-positives-filter",
   "metadata": {},
   "source": [
    "`Positives(values)` does the same job as `filter(lambda v: v > 0, values)`. Writing it by hand shows what `filter()` does inside: pull values from the source until one passes the test."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49924d7b",
   "metadata": {},
   "source": [
    "### Why Iterators Are Single-Use\n",
    "\n",
    "Now you can see why the built-in iterators earlier in this section work only once. An iterator's `__iter__()` returns `self`, so a `Countdown` object keeps its position after a loop ends, and a second loop over the *same object* finds nothing. A list is different: it is an iterable, not an iterator, and its `__iter__()` returns a new list iterator for each loop:"
   ]
  },
  {
   "cell_type": "code",
   "id": "852e00b2",
   "metadata": {},
   "source": [
    "countdown = Countdown(3)\n",
    "print(list(countdown))   # [3, 2, 1]\n",
    "print(list(countdown))   # []: the same object is already at the end\n",
    "\n",
    "numbers = [3, 2, 1]\n",
    "print(list(numbers))     # [3, 2, 1]\n",
    "print(list(numbers))     # [3, 2, 1]: each loop gets a fresh list iterator"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "f7ddafaa",
   "metadata": {},
   "source": [
    "To loop again, create a new object such as `Countdown(3)`. {doc}`1102-generators` shows how to write a class that can be looped over many times, using a generator for `__iter__()`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-endless",
   "metadata": {},
   "source": [
    "### Iterators That Never End\n",
    "\n",
    "An iterator does not have to end. If `__next__()` never raises `StopIteration`, the iterator produces a new value every time it is asked, forever. That sounds odd at first, but many real tasks have no natural last value:\n",
    "\n",
    "- **Counters and IDs.** Ticket numbers, order numbers, and record IDs: each new customer or record needs the next number, and there is no final one.\n",
    "- **Repeating patterns.** Taking turns in a fixed order, such as assigning reviewers round-robin or alternating the colors of table rows: when the pattern reaches its end, it starts over.\n",
    "- **Streams and simulations.** Sensor readings, new lines in a live log, or the next step of a simulation: values keep coming for as long as the program keeps asking.\n",
    "\n",
    "An endless iterator is safe as long as *something else* decides when to stop. `list()`, `sum()`, `max()`, and a plain `for` loop never stop on their own, because they keep asking until `StopIteration`, which never comes: the cell runs forever, and with `list()`, memory keeps growing too. Three ways do stop:\n",
    "\n",
    "1. Call `next()` a fixed number of times.\n",
    "2. Pair it with a finite iterable in `zip()`, with the finite one first, which stops when the shorter input runs out.\n",
    "3. Loop over it with `for` and leave with `break` when a condition is met.\n",
    "\n",
    "`TicketNumbers` hands out ticket numbers forever. Notice that its `__next__()` has no `StopIteration` at all:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-it-tickets",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TicketNumbers:\n",
    "    \"\"\"Hands out ticket numbers 1001, 1002, ... forever.\"\"\"\n",
    "\n",
    "    def __init__(self, start=1001):\n",
    "        self.current = start\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    def __next__(self):\n",
    "        value = self.current\n",
    "        self.current += 1\n",
    "        return value                  # no StopIteration: never runs out\n",
    "\n",
    "tickets = TicketNumbers()\n",
    "\n",
    "# 1. A fixed number of next() calls\n",
    "print(next(tickets), next(tickets))  # 1001 1002\n",
    "\n",
    "# 2. zip() stops when the finite list runs out\n",
    "customers = ['Ana', 'Ben', 'Cy']\n",
    "for name, number in zip(customers, tickets):\n",
    "    print(name, number)              # Ana 1003, Ben 1004, Cy 1005\n",
    "\n",
    "# 3. A for loop with its own exit\n",
    "for number in tickets:\n",
    "    if number > 1007:\n",
    "        break\n",
    "    print(number, end=' ')           # 1006 1007\n",
    "print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-endless-after",
   "metadata": {},
   "source": [
    "The same `tickets` object serves all three: each use picks up where the last one stopped, because the iterator keeps its position. That shared position is why argument order in `zip()` matters. `zip()` pulls from its inputs left to right, so `zip(customers, tickets)` sees that `customers` has run out before it asks for another ticket. With `zip(tickets, customers)`, it would take ticket `1006` first, find no customer for it, and that ticket would be lost: loop 3 would print only `1007`. Put the finite iterable first.\n",
    "\n",
    "{doc}`1103-pipelines` introduces `itertools`, whose `count()` and `cycle()` give you ready-made endless iterators and whose `islice()` takes a fixed number of values from one. The exercise below builds a repeating-pattern iterator of your own."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d15e217",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Cycling Iterator\n",
    "#   Implement a `Cycle` iterator that loops through a sequence forever.\n",
    "#   Example: Cycle(['R', 'G', 'B']) produces R, G, B, R, G, B, R, ...\n",
    "#   1. Store the sequence and the current index.\n",
    "#   2. `__next__` returns the item at the current index and advances; wraps with modulo.\n",
    "#   3. Test: collect the first 7 values from Cycle([1, 2, 3]) → [1, 2, 3, 1, 2, 3, 1].\n",
    "#   Hint: Cycle never ends, so do not loop over it directly. Collect the\n",
    "#   values with next() inside a `for _ in range(7)` loop.\n",
    "#   Print exactly:\n",
    "#   [1, 2, 3, 1, 2, 3, 1]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5d4c0e83",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 1, 2, 3, 1]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "class Cycle:\n",
    "    def __init__(self, sequence):\n",
    "        self.sequence = list(sequence)\n",
    "        self.index = 0\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    def __next__(self):\n",
    "        if not self.sequence:          # empty input: nothing to cycle\n",
    "            raise StopIteration\n",
    "        value = self.sequence[self.index]\n",
    "        self.index = (self.index + 1) % len(self.sequence)\n",
    "        return value\n",
    "\n",
    "cycle = Cycle([1, 2, 3])\n",
    "values = []\n",
    "for _ in range(7):          # Cycle never ends, so stop after 7 values\n",
    "    values.append(next(cycle))\n",
    "print(values)               # [1, 2, 3, 1, 2, 3, 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-it-exercises",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines the iterator protocol, built-in lazy iterators, and a custom iterator class.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-it-words-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Word Iterator\n",
    "#   1. Implement a class `Words(text)` with __iter__ and __next__ that returns\n",
    "#      the words of `text` one at a time, lowercased, with the punctuation\n",
    "#      characters \".,!?\" stripped from each end.\n",
    "#      Raise StopIteration after the last word.\n",
    "#   2. Print the first word of Words(text) with next().\n",
    "#   3. Use enumerate() with a fresh Words(text) to print every word\n",
    "#      numbered from 1, e.g. \"1. iterators\".\n",
    "#   4. Use filter() with a fresh Words(text) to print the list of words\n",
    "#      longer than 5 letters.\n",
    "#   Print exactly:\n",
    "#   iterators\n",
    "#   1. iterators\n",
    "#   2. save\n",
    "#   3. memory\n",
    "#   4. generators\n",
    "#   5. save\n",
    "#   6. effort\n",
    "#   ['iterators', 'memory', 'generators', 'effort']\n",
    "text = \"Iterators save memory. Generators save effort!\"\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ch11-it-words-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iterators\n",
      "1. iterators\n",
      "2. save\n",
      "3. memory\n",
      "4. generators\n",
      "5. save\n",
      "6. effort\n",
      "['iterators', 'memory', 'generators', 'effort']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "text = \"Iterators save memory. Generators save effort!\"\n",
    "\n",
    "class Words:\n",
    "    \"\"\"Iterate over the lowercase words of a text, punctuation stripped.\"\"\"\n",
    "\n",
    "    def __init__(self, text):\n",
    "        self.words = text.split()\n",
    "        self.index = 0\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    def __next__(self):\n",
    "        if self.index >= len(self.words):\n",
    "            raise StopIteration\n",
    "        word = self.words[self.index].strip(\".,!?\").lower()\n",
    "        self.index += 1\n",
    "        return word\n",
    "\n",
    "print(next(Words(text)))   # iterators\n",
    "\n",
    "for i, word in enumerate(Words(text), start=1):\n",
    "    print(f\"{i}. {word}\")\n",
    "\n",
    "print(list(filter(lambda w: len(w) > 5, Words(text))))\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
