← Back to Articles
Tutorial

python-generators

Learn python-generators in Python with step-by-step examples.

Python generators are a special type of iterable, like lists or tuples, but instead of storing all their values in memory, they generate the values on the fly using the 'yield' keyword. A generator function returns an iterator that yields one value at a time, pausing after each yield and resuming from there on the next call.

Generators are useful because they allow you to work with large datasets or infinite sequences without consuming a lot of memory. Since they only produce items as needed, they are memory efficient and can help improve the performance of your programs.

Common use cases for generators include reading large files line by line, generating infinite sequences (such as Fibonacci numbers), streaming data, or any situation where you want to process items one at a time rather than all at once.

Code Examples

Example 1

def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)

More Python Tutorials