Python provides the capability to create your own iterator function using a construct known as a generator.
π‘ A generator is a unique kind of function. Unlike traditional functions that return a single value, a generator returns a special object — an iterator, which can produce a sequence of values over time.
The key feature distinguishing a generator function is its usage of the yield
statement, as opposed to the return
statement found in ordinary functions.
The yield
statement allows the function to produce values one at a time, pausing in-between, instead of computing them all at once. This can make your code more efficient and memory-friendly when dealing with large data sets.
When a generator function is called, it doesn’t actually run the code in the function. Instead, it returns a generator object. This object can then be iterated over (for example, in a for
loop or by using the next()
function) to execute the function and retrieve the values it yields, one by one, as needed.
You can return a generator from a function by using the yield
keyword. Here’s an example:
def fibonacci(): a, b = 0, 1 while True: yield a b, a = a + b, b
In this example, the fibonacci
function is a generator function because it uses the yield
keyword. Every time you call next()
on a generator created by this function, it will yield the next Fibonacci number.
(If you don’t understand the Fibonacci series yet, check out my fun blog tutorial:) π
π‘ Recommended: Fibonacci in One Line Python
Here’s how you might use this generator:
gen = fibonacci() print(next(gen)) # Output: 0 print(next(gen)) # Output: 1 print(next(gen)) # Output: 1 print(next(gen)) # Output: 2 print(next(gen)) # Output: 3
Each time next()
is called, the function’s state is preserved, so it can remember the values of a
and b
. The next time next()
is called, the function picks up where it left off and yields the next value.
π Note: Generator functions return a special type of iterator, which is the generator. When the generator’s __next__()
method (or the built-in function next()
) is called, the function runs until it hits a yield
statement, then it yields its value and pauses.
When __next__()
is called again, the function resumes running from where it left off, starting after the yield
statement, until it hits another yield
statement (or returns, which signals the generator is done).
π‘ Recommended: Python Generator Expressions