⚙️ Advanced Python
Generators & Iterators
Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data.
● Advanced
📖 Based on: Python Docs, Fluent Python — Luciano Ramalho
📋 Table of Contents
1 · Generator Functions
When a generator function is called, it returns a generator object without even beginning execution of the function. When next() is called, the function resumes execution until a yield is reached.
Textbook Definition
"A generator is a function that remembers its state between calls. Unlike regular functions that start from the top every time, generators 'resume' where they left off." — Fluent Python
Python
def countdown(n): while n > 0: yield n n -= 1 counter = countdown(3) print(next(counter)) # 3 print(next(counter)) # 2
🔁 Return Value
Calling a generator function returns a generator iterator object. It does not return the value yielded; you must iterate over the generator object to retrieve values.