Sobes.tech
Junior — Middle

How does a generator help reduce memory usage in a program?

sobes.tech AI

Answer from AI

A generator in Python allows creating iterators that return elements one by one, without loading the entire sequence into memory at once. This reduces memory usage, especially when working with large amounts of data.

Instead of creating a list of all elements at once, the generator computes and returns the next element only upon request.

Example of a generator:

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

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

In this example, numbers from 1 to 1,000,000 are not stored entirely in memory but are generated one by one, saving memory.