Sobes.tech
Junior — Middle

What tasks can be solved with a generator?

sobes.tech AI

Answer from AI

Generators in Python allow efficient handling of large data volumes without loading them entirely into memory. They can:

  • Generate elements sequentially one by one, saving memory.
  • Implement lazy evaluations, such as infinite sequences.
  • Simplify code for iterators by avoiding the creation of classes with __iter__ and __next__ methods.

Example of a generator that returns squares of numbers from 0 to n-1:

def squares(n):
    for i in range(n):
        yield i * i

for val in squares(5):
    print(val)