Member-only story
Generators are a powerful feature in Python, but they’re often overlooked. In this article, we’ll explore how generators can simplify your code and make your Python programs more efficient.
Let’s start with the basic for loop in Python. The for loop is used to iterate over a sequence, like a list or a string. For example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This will print each fruit in the list, one by one. Simple enough, right?
Now, let’s say you want to generate a sequence of numbers, like the first 10 even numbers. You could do it like this:
even_numbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
for number in even_numbers:
print(number)
This works, but it requires you to create a whole list of even numbers, even if you only need to use them one at a time. That’s where generators come in.
A generator is a special kind of function that can be used to create sequences of values on the fly, without needing to store them all in memory at once. Here’s how you can use a generator to print the first 10 even numbers:
def even_numbers_generator():
number = 2
while number <= 20:
yield number
number += 2
for number…