Understanding Python Generators
Python generators are a special type of function that allow you to create iterators. Unlike regular functions, which return a value and then terminate, generators can be paused and resumed, allowing them to generate a sequence of values over time.
Generators are particularly useful when working with large or infinite data sets, as they can produce values one at a time, rather than generating the entire data set at once and storing it in memory.
The key difference between a generator and a regular function is the use of the yield
keyword instead of the return
keyword. When a generator function is called, it returns a generator object, which can then be iterated over to retrieve the values generated by the function.
Here's a simple example of a generator function that generates the first n
Fibonacci numbers:
def fibonacci(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
In this example, the fibonacci()
function is a generator function that uses the yield
keyword to return each Fibonacci number, rather than returning the entire sequence at once.
To use this generator, you can create an instance of the fibonacci()
function and then iterate over the values it generates:
fib = fibonacci(10)
for num in fib:
print(num)
This will output the first 10 Fibonacci numbers:
0
1
1
2
3
5
8
13
21
34
Generators can also be used in a wide variety of other applications, such as processing large data sets, implementing coroutines, and creating custom data structures.