Lesson 31 of 55 · Python
Generators and Iterators
Duration: 20 minutes
Lesson 31 of 55 · Python
Duration: 20 minutes
yield keyword, turning a regular function into an iterator that emits values on demand.\n\npython\ndef fib(limit):\n a, b = 0, 1\n while a < limit:\n yield a\n a, b = b, a + b\n\nfor n in fib(20):\n print(n, end=' ')\n# Output: 0 1 1 2 3 5 8 13\n\n\nGenerators are memory‑efficient for large data streams because they never store the whole sequence at once.\n