{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "61d929bd",
   "metadata": {},
   "source": [
    "# Generators"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0fce573",
   "metadata": {},
   "source": [
    "In {doc}`1101-iterators` you wrote iterator classes by hand: `__init__()` to set up a position, `__iter__()` to return `self`, and `__next__()` to update the position and raise `StopIteration` at the end. A **generator** gives you the same kind of iterator with far less code. You write an ordinary function that uses `yield` to hand out each value, and Python builds the iterator, remembers the position, and raises `StopIteration` when the function finishes.\n",
    "\n",
    "Like the built-in lazy iterators, generators produce values one at a time, only when asked, so they can handle large files, data streams, and sequences with no end without building a whole collection in memory. This section covers generator functions, generator expressions (the lazy counterpart of list comprehensions), and how functions such as `sum()`, `any()`, `all()`, and `next()` consume them. The next section, {doc}`1103-pipelines`, chains generators together into data pipelines."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ],
   "id": "contents"
  },
  {
   "cell_type": "markdown",
   "id": "197a2fe2",
   "metadata": {},
   "source": [
    "## Generator Functions\n",
    "\n",
    "A **generator function** looks like a regular function but contains `yield`. `yield` is the keyword that makes a function a **generator**. `yield` works like a `return` that pauses instead of ending: it hands a value back to whoever called `next()`, freezes the function at that line with its local variables intact, and continues from there on the next `next()`.\n",
    "\n",
    "```python\n",
    "def my_gen():\n",
    "    yield 1   # pauses here on first next()\n",
    "    yield 2   # pauses here on second next()\n",
    "    yield 3   # pauses here on third next()\n",
    "    # function returns → StopIteration is raised automatically\n",
    "```\n",
    "\n",
    "How `yield` compares with `return`:\n",
    "\n",
    "| | `return` | `yield` |\n",
    "|---|---|---|\n",
    "| Gives back a value | Once | Once per `next()` call, so possibly many times |\n",
    "| Afterward the function | Ends, and its local variables are gone | Pauses, and its local variables are kept |\n",
    "| Calling the function | Runs the body | Returns a **generator object**; the body runs on `next()` |\n",
    "\n",
    "Values are therefore produced **lazily**, only when requested.\n",
    "\n",
    "If `yield` appears anywhere in the body, even in a branch that never runs, calling the function no longer executes the body: the call returns a generator object. A generator can also contain `return`, which simply ends it; Python then raises `StopIteration`. To hand out every value from another iterable, use `yield from`, covered in {doc}`1103-pipelines`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-197a2fe2",
   "metadata": {},
   "source": [
    "```{index} generator function, yield keyword, generator object\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9be6a20c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_up_to(max_count):\n",
    "    \"\"\"Yields integers 1, 2, ..., max_count.\"\"\"\n",
    "    n = 1\n",
    "    while n <= max_count:\n",
    "        yield n\n",
    "        n += 1\n",
    "\n",
    "# Calling the function returns a generator object; nothing executes yet\n",
    "gen = count_up_to(5)\n",
    "print(type(gen))          # <class 'generator'>\n",
    "\n",
    "# Values are produced one at a time\n",
    "print(next(gen))          # 1\n",
    "print(next(gen))          # 2\n",
    "\n",
    "# for loops consume the remaining values\n",
    "for val in gen:\n",
    "    print(val, end=' ')   # 3 4 5\n",
    "print()\n",
    "\n",
    "# A fresh generator starts from the beginning\n",
    "print(list(count_up_to(5)))   # [1, 2, 3, 4, 5]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0833ae12",
   "metadata": {},
   "source": [
    "### Watching a Generator Pause\n",
    "\n",
    "The comments above describe the pausing, but you can watch it happen. The generator below prints a message each time its body runs, so the output shows exactly when the code inside the function executes:"
   ]
  },
  {
   "cell_type": "code",
   "id": "2c21d87e",
   "metadata": {},
   "source": [
    "def noisy_gen():\n",
    "    print(\"  body starts\")\n",
    "    yield 1\n",
    "    print(\"  resumed after yield 1\")\n",
    "    yield 2\n",
    "    print(\"  resumed after yield 2, reaching the end\")\n",
    "\n",
    "gen = noisy_gen()\n",
    "print(\"generator created\")       # nothing from the body has printed yet\n",
    "\n",
    "print(\"next ->\", next(gen))      # runs the body up to the first yield\n",
    "print(\"next ->\", next(gen))      # resumes right after yield 1\n",
    "\n",
    "try:\n",
    "    next(gen)                    # resumes, runs to the end, raises StopIteration\n",
    "except StopIteration:\n",
    "    print(\"StopIteration: the body finished\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "97e394c8",
   "metadata": {},
   "source": [
    "Read the output in order. Creating the generator printed nothing, so the body had not started. Each `next()` ran only as far as the next `yield`, and each call resumed exactly where the last one paused. When the body ran off its end, Python raised `StopIteration` for you, which is the same signal a custom iterator's `__next__()` raises by hand."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-gen-evens-q",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Even Numbers Generator\n",
    "#   1. Write a generator function `evens_up_to(limit)` that yields the even\n",
    "#      numbers 0, 2, 4, ... up to and including `limit`.\n",
    "#   2. Create a generator with evens_up_to(10) and print its first two values\n",
    "#      with next().\n",
    "#   3. Print list() of the same generator to see the values that are left.\n",
    "#   Print exactly:\n",
    "#   0\n",
    "#   2\n",
    "#   [4, 6, 8, 10]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ch11-gen-evens-s",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "2\n",
      "[4, 6, 8, 10]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def evens_up_to(limit):\n",
    "    n = 0\n",
    "    while n <= limit:\n",
    "        yield n\n",
    "        n += 2\n",
    "\n",
    "gen = evens_up_to(10)\n",
    "print(next(gen))    # 0\n",
    "print(next(gen))    # 2\n",
    "print(list(gen))    # [4, 6, 8, 10]  (resumes after 2)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0b79634",
   "metadata": {},
   "source": [
    "### From Iterator Classes to Generators\n",
    "\n",
    "In {doc}`1101-iterators` you wrote `Countdown` as a class with `__init__()`, `__iter__()`, and `__next__()`, and you saved the position in `self.current` by hand. A generator function does the same job in a few lines, because Python saves the local variables and the position for you at each **`yield`**:"
   ]
  },
  {
   "cell_type": "code",
   "id": "a16397cf",
   "metadata": {},
   "source": [
    "# The class version from Iterators\n",
    "class Countdown:\n",
    "    def __init__(self, start):\n",
    "        self.current = start\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\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",
    "# The generator version: same behavior, no protocol methods to write\n",
    "def countdown(start):\n",
    "    current = start\n",
    "    while current > 0:\n",
    "        yield current\n",
    "        current -= 1\n",
    "\n",
    "print(list(Countdown(5)))   # [5, 4, 3, 2, 1]\n",
    "print(list(countdown(5)))   # [5, 4, 3, 2, 1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ch11-gen-is-iter-lead",
   "metadata": {},
   "source": [
    "**Every generator is an iterator**, but not every iterator is a generator. *Iterator* names the protocol: any object whose `__iter__()` returns itself and whose `__next__()` hands out the next value. A generator is one convenient way to get such an object without writing the class:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch11-gen-is-iter",
   "metadata": {},
   "outputs": [],
   "source": [
    "gen = countdown(3)\n",
    "print(iter(gen) is gen)   # True: __iter__() returns the generator itself\n",
    "print(next(gen))          # 3: __next__() hands out the next value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch11-gen-vs-iter",
   "metadata": {},
   "source": [
    "The two ways of making an iterator differ mainly in who does the bookkeeping:\n",
    "\n",
    "|    | | Iterator class | Generator |\n",
    "| - |---|---|---|\n",
    "| 1 | How you create it | A class with `__iter__()` (returns `self`) and `__next__()` | A function containing `yield`, or a generator expression `( … )`, covered in Generator Expressions below |\n",
    "| 2 | Where the position is kept | In attributes you manage, such as `self.current` | Automatically, in the paused function's local variables |\n",
    "| 3 | How it ends | `__next__()` raises `StopIteration` | The function body finishes, and Python raises `StopIteration` for you |\n",
    "| 4 | Access from outside | Other code can read its attributes or call methods you add, such as a `reset()` method | Its state is hidden inside the paused function |\n",
    "| 5 | Typical use | Iterators that need attributes or methods other code uses | Pipelines, streams, lazy sequences, and most everyday cases |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4bc80e7",
   "metadata": {},
   "source": [
    "```{index} reusable iterable\n",
    "```\n",
    "\n",
    "Both kinds of iterator are single-use: once a `Countdown` object or a `countdown()` generator reaches the end, it stays there. A class becomes **reusable** when its `__iter__()` returns a *new* iterator each time instead of `self`. The simplest way to do that is to write `__iter__()` as a generator function. Each time the object is iterated, whether by a `for` loop, `list()`, or anything else, Python calls `iter()`, which calls `__iter__()`, which starts a fresh generator:"
   ]
  },
  {
   "cell_type": "code",
   "id": "8729ed2d",
   "metadata": {},
   "source": [
    "class CountdownRange:\n",
    "    \"\"\"A reusable iterable: every loop starts again from `start`.\"\"\"\n",
    "\n",
    "    def __init__(self, start):\n",
    "        self.start = start\n",
    "\n",
    "    def __iter__(self):              # a generator method: yield makes it one\n",
    "        current = self.start\n",
    "        while current > 0:\n",
    "            yield current\n",
    "            current -= 1\n",
    "\n",
    "timer = CountdownRange(3)\n",
    "for n in timer:\n",
    "    print(n)        # 3, 2, 1\n",
    "for n in timer:\n",
    "    print(n)        # 3, 2, 1 again: a fresh generator each time\n",
    "\n",
    "print(list(timer))   # [3, 2, 1]\n",
    "print(list(timer))   # [3, 2, 1]: a fresh generator each time, like a list"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "4f2d446d",
   "metadata": {},
   "source": [
    "This is how a list behaves: the list is an *iterable* that stores the data, and each `iter()` call produces a separate *iterator* that tracks one pass. `CountdownRange` works the same way: the class holds the data, and the generator does the stepping.\n",
    "\n",
    "Default to a generator: it is shorter and harder to get wrong. Write a full `__iter__()`/`__next__()` class only when the iterator needs an interface beyond `next()`, such as a `reset()` method or a `remaining` attribute that other code reads."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62414b74",
   "metadata": {},
   "source": [
    "## Generator Expressions\n",
    "\n",
    "```{index} generator expression\n",
    "```\n",
    "\n",
    "A **generator expression** has the same syntax as a list comprehension, but uses `()` instead of `[]`. The result is a generator, not a list; values are computed on demand.\n",
    "\n",
    "```python\n",
    "# List comprehension: builds the entire list in memory immediately\n",
    "squares_list = [x ** 2 for x in range(1_000_000)]   # about 40 MB in total\n",
    "\n",
    "# Generator expression: produces values one at a time\n",
    "squares_gen  = (x ** 2 for x in range(1_000_000))   # about 200 bytes\n",
    "\n",
    "# Python does not have tuple comprehension. Parentheses around a for clause always produce a generator expression.\n",
    "```\n",
    "\n",
    "The list's total has two parts. `sys.getsizeof(squares_list)` reports only the list's own array of references, about 8 MB; the one million integer objects it points to take about 32 MB more. The generator stores none of the values, only its current state.\n",
    "\n",
    "Prefer a generator expression when you only need the values once, especially when the data is large."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d402d082",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "List size:      8,448,728 bytes\n",
      "Generator size: 200 bytes\n",
      "Sum of squares 0-1000: 333833500\n",
      "First multiple of 7:   7\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "\n",
    "# Compare memory: list vs generator\n",
    "n = 1_000_000\n",
    "squares_list = [x ** 2 for x in range(n)]\n",
    "squares_gen  = (x ** 2 for x in range(n))\n",
    "\n",
    "print(f\"List size:      {sys.getsizeof(squares_list):,} bytes\")\n",
    "print(f\"Generator size: {sys.getsizeof(squares_gen):,} bytes\")\n",
    "\n",
    "# Generator expressions compose well with sum(), max(), any(), etc.\n",
    "total       = sum(x ** 2 for x in range(1001))             \t# no intermediate list\n",
    "first_mult7 = next(x for x in range(1, 100) if x % 7 == 0) \t# 7\n",
    "print(f\"Sum of squares 0-1000: {total}\")\n",
    "print(f\"First multiple of 7:   {first_mult7}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4144b629",
   "metadata": {},
   "source": [
    "### Working with Generator Expressions\n",
    "\n",
    "A generator is not a list, so a few list habits do not carry over:\n",
    "\n",
    "- **No `len()` and no indexing.** A generator does not know how many values it will produce, so `len(gen)` and `gen[0]` raise `TypeError`. To count the items, add `1` for each one: `sum(1 for x in items if condition)`.\n",
    "- **`next()` can take a default.** `next(gen)` raises `StopIteration` when nothing is left. `next(gen, default)` returns `default` instead, which is the safe way to ask for \"the first match, if any\".\n",
    "- **Parentheses.** You can drop the generator's own parentheses only when it is the *only* argument, as in `sum(x for x in nums)`. With another argument, keep them: `sorted((x for x in nums), reverse=True)`."
   ]
  },
  {
   "cell_type": "code",
   "id": "954db631",
   "metadata": {},
   "source": [
    "nums = [4, -1, 7, 0, 3, -2, 8]\n",
    "\n",
    "# Counting: sum one 1 per matching item (len() does not work on a generator)\n",
    "negatives = sum(1 for n in nums if n < 0)\n",
    "print(\"Negatives:\", negatives)                            # 2\n",
    "\n",
    "try:\n",
    "    len(n for n in nums)\n",
    "except TypeError as e:\n",
    "    print(\"TypeError:\", e)\n",
    "\n",
    "# next() with a default: no StopIteration when nothing matches\n",
    "print(next((n for n in nums if n > 5), None))             # default to None. 7\n",
    "print(next((n for n in nums if n > 100), None))           # default to None\n",
    "\n",
    "# A second argument means the generator needs its own parentheses\n",
    "print(sorted((n for n in nums if n > 0), reverse=True))   # [8, 7, 4, 3]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a0e49f4",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Running Total Generator\n",
    "#   1. Write a generator function `running_total(numbers)` that yields the\n",
    "#      cumulative sum after each element.\n",
    "#      Example: running_total([1, 4, 2, 8]) yields 1, 5, 7, 15.\n",
    "#   2. Write a generator expression `even_squares_gen` that yields the squares\n",
    "#      of even numbers from 0 to 19 (i.e., 0, 4, 16, 36, 64, 100, ..., 324).\n",
    "#   3. Print list() of each.\n",
    "#   Print exactly:\n",
    "#   [1, 5, 7, 15]\n",
    "#   [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93fafd97",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "[1, 5, 7, 15]\n[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]\n"
    }
   ],
   "source": [
    "### Solution\n",
    "def running_total(numbers):\n",
    "    total = 0\n",
    "    for n in numbers:\n",
    "        total += n\n",
    "        yield total\n",
    "\n",
    "print(list(running_total([1, 4, 2, 8])))   # [1, 5, 7, 15]\n",
    "\n",
    "even_squares_gen = (x ** 2 for x in range(20) if x % 2 == 0)\n",
    "print(list(even_squares_gen))   # [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e86cd25c",
   "source": [
    "### `any()` and `all()` with Generator Expressions\n",
    "\n",
    "```{index} any(), all(), short-circuit evaluation\n",
    "```\n",
    "\n",
    "In {doc}`Lists <../06-collections/0601-lists>` you used `any()` and `all()` with list comprehensions. Now that you know generator expressions, you can drop the brackets:\n",
    "\n",
    "```python\n",
    "# list comprehension: builds the full list, then checks\n",
    "any([x > 0 for x in values])\n",
    "\n",
    "# generator expression: stops as soon as the result is known\n",
    "any(x > 0 for x in values)\n",
    "```\n",
    "\n",
    "The generator version is more efficient for two reasons: it never builds an intermediate list, and it lets the **short-circuit** save real work. `any()` stops at the first truthy value and `all()` at the first falsy one, with either a list or a generator. But with a list comprehension, every test has already run before `any()` starts. With a generator expression, the remaining tests are never computed."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "id": "e35f9715",
   "source": [
    "data = [4, -1, 7, 0, 3, -2, 8]\n",
    "\n",
    "# any() stops the moment it finds a True value; the rest is never checked\n",
    "print(any(x < 0 for x in data))      # True  (stops at -1)\n",
    "\n",
    "# all() stops the moment it finds a False value\n",
    "print(all(x > 0 for x in data))      # False (stops at -1)\n",
    "\n",
    "# Common data-validation patterns\n",
    "scores = [82, 91, 74, 88, 65]\n",
    "print(all(s >= 60 for s in scores))  # True: all passed\n",
    "print(any(s >= 90 for s in scores))  # True: at least one A"
   ],
   "metadata": {},
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "7aadfd26",
   "source": [
    "### Exercise: any() and all() with Generator Expressions\n",
    "# 1. Use any() with a generator expression to check if any sale exceeds 2000.\n",
    "# 2. Use all() with a generator expression to check if all sales are above 400.\n",
    "# 3. Use next() with a generator expression to find the first sale above 1000.\n",
    "# 4. Use next() with a default of None to look for a sale above 5000.\n",
    "# Print exactly:\n",
    "# True\n",
    "# True\n",
    "# 1200\n",
    "# None\n",
    "sales = [1200, 850, 2100, 430, 975, 1600]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ],
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "2e02a53a",
   "source": [
    "### Solution\n",
    "sales = [1200, 850, 2100, 430, 975, 1600]\n",
    "\n",
    "print(any(s > 2000 for s in sales))        # True: 2100 qualifies\n",
    "print(all(s > 400 for s in sales))         # True: minimum is 430\n",
    "print(next(s for s in sales if s > 1000))  # 1200: first match\n",
    "print(next((s for s in sales if s > 5000), None))  # None: no sale qualifies"
   ],
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "execution_count": null,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nTrue\n1200\nNone\n"
    }
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42d84a07",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This task combines a generator function, generator expressions, `sum()`, `all()`, and `next()` with a default.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd21a86e",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Order Totals\n",
    "#   1. Write a generator function `order_totals(orders)` that yields\n",
    "#      qty * price for each (item, qty, price) tuple, skipping any order\n",
    "#      whose qty is 0 or less.\n",
    "#   2. Use sum() to print the grand total of all order totals.\n",
    "#   3. Use sum() with a generator expression to count the orders whose\n",
    "#      total is at least 20.\n",
    "#   4. Use all() with a generator expression to check that every order\n",
    "#      total is under 100.\n",
    "#   5. Use next() with a generator expression and a default of None to\n",
    "#      find the first order total above 30.\n",
    "#   Call order_totals(orders) again for each step: a generator is used up\n",
    "#   after one pass.\n",
    "#   Print exactly:\n",
    "#   Grand total: 77.0\n",
    "#   Orders of 20 or more: 2\n",
    "#   All under 100: True\n",
    "#   First above 30: 35.0\n",
    "orders = [(\"pen\", 4, 1.5), (\"mug\", 2, 12.0), (\"book\", 0, 20.0),\n",
    "          (\"lamp\", 1, 35.0), (\"ink\", 3, 4.0)]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b4d9e8c",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Grand total: 77.0\nOrders of 20 or more: 2\nAll under 100: True\nFirst above 30: 35.0\n"
    }
   ],
   "source": [
    "### Solution\n",
    "orders = [(\"pen\", 4, 1.5), (\"mug\", 2, 12.0), (\"book\", 0, 20.0),\n",
    "          (\"lamp\", 1, 35.0), (\"ink\", 3, 4.0)]\n",
    "\n",
    "def order_totals(orders):\n",
    "    for item, qty, price in orders:\n",
    "        if qty > 0:                       # skip empty orders\n",
    "            yield qty * price\n",
    "\n",
    "print(\"Grand total:\", sum(order_totals(orders)))\n",
    "print(\"Orders of 20 or more:\", sum(1 for t in order_totals(orders) if t >= 20))\n",
    "print(\"All under 100:\", all(t < 100 for t in order_totals(orders)))\n",
    "print(\"First above 30:\", next((t for t in order_totals(orders) if t > 30), None))\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
