DEV Community

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

Posted on

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.

Top comments (0)