DEV Community

Cover image for Example of Generators in Python
Luan Gomes
Luan Gomes

Posted on

2 2

Example of Generators in Python

Memory management is very important during software development, to scale it in a healthy way, knowledge of its language functions must provide the performance that will make a difference.

Let's get to know generators in Python, what it is, how to use it and the relationship with memory management.

We can define generators as iterators, with the difference that the value is not stored, the execution occurs on the fly.

The best way to use is through functions, that you can get the value as the generation occur.

def generator_function():
    for i in range(5):
        yield i

# Output: 0
# 1
# 2
# 3
# 4
Enter fullscreen mode Exit fullscreen mode

A good use is the fibonacci numbers, if we pass a function a like that...

def fibon(n):
    a = b = 1
    result = []
    for i in range(n):
        result.append(a)
        a, b = b, a + b
    return result

for x in fibon(1000000):
    print(x)
Enter fullscreen mode Exit fullscreen mode

We will probably run out of memory, because the result is being stored in a array.

With the generators...

def fibon(n):
    a = b = 1
    for i in range(n):
        yield a
        a, b = b, a + b
Enter fullscreen mode Exit fullscreen mode

We will use far fewer resources because there is no value being stored.

This was just a simple example, but you had a view how the things work, the generators are powerful and a good friend of your system.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up