Generators in Python
Generators in Python are a type of iterable, like lists or tuples, but unlike lists or tuples, they do not store all of their values in memory. Instead, they generate values on the fly as they are needed. This makes them very useful for working with large datasets or in situations where memory is limited.
Generators are defined using a function that contains at least one yield
statement. When the function is called, it returns a generator object that can be iterated over using a for
loop, or by calling the built-in next()
function.
Let’s take a look at an example of a generator function:
def countdown(n):
while n > 0:
yield n
n -= 1
In this example, the countdown()
function takes a number n
as an argument and generates a sequence of numbers from n
down to 1
. The yield
statement is used to produce each value in the sequence.
To use this generator function, we can simply call it and iterate over the returned generator object:
for i in countdown(5):
print(i)
# The output will be:
5
4
3
2
1
Generators can also be used to create an infinite sequence of values. For example, the following generator function will generate an infinite sequence of Fibonacci numbers:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
To use this generator function, we can simply call it and iterate over the returned generator object:
fib = fibonacci()
for i in range(10):
print(next(fib))
# The output will be:
0
1
1
2
3
5
8
13
21
34
As we can see, the fibonacci()
generator function generates an infinite sequence of Fibonacci numbers, but we can still use it to generate a finite number of values by using the next()
function to extract a certain number of values from the generator object.
In conclusion, generators in Python are a powerful tool for generating sequences of values on the fly, without requiring large amounts of memory or processing power. They can be used in a wide range of applications, from generating sequences of numbers to processing large datasets, and are a valuable tool for any Python programmer to have in their toolkit.