What are Python generators?
Python generators are a simple and powerful tool for creating iterators. Unlike regular functions that return a single value and exit, generators use the yield keyword to return a sequence of values, one at a time, resuming exactly where they left off each time they are called. This makes them memory-efficient, especially for working with large datasets or streams of data, as they don't store the entire sequence in memory.
A generator is created like a normal function but uses yield instead of return. Each time the generator’s next() method is called, it resumes from where it last yielded a value. This allows for lazy evaluation, which means values are computed only when needed. This can be particularly useful in loops or pipelines where only part of a data sequence is needed at a time.
Here’s a simple example:
def countdown(n):
while n > 0:
yield n
n -= 1
When you call countdown(5), it doesn’t run the function immediately. Instead, it returns a generator object. You can then use it in a loop:
for number in countdown(5):
print(number)
This will print numbers from 5 to 1.
Generators are ideal when you're dealing with tasks like reading large files line by line, streaming data, or creating infinite sequences. They provide a clean and Pythonic way to handle iteration while saving memory and improving performance.
If you’re just getting started with coding, learning how to use generators can help you write more efficient and elegant code. To dive deeper into this topic and others like it, consider starting with a python course for beginners.