Sobes.tech
Middle

What is a generator function?

sobes.tech AI

Answer from AI

A generator function is a special type of function in Python that uses the keyword yield instead of return to return a value. Unlike regular functions, which terminate after the first return, a generator function "freezes" its execution after each yield, preserving its state. When called again, it resumes execution from where it left off. This allows creating iterators that produce values sequentially, on demand, without loading all data into memory at once.

Advantages of generator functions:

  • Memory efficiency: Values are generated on demand, which is especially useful when working with large datasets or infinite sequences.
  • Lazy evaluation: Computations are performed only when the value is actually needed.
  • Simpler iterator creation: The syntax of generator functions is more intuitive than creating classes that implement the iterator protocol (__iter__ and __next__).
# Example of a simple generator function
def simple_generator():
    yield 1
    yield 2
    yield 3

# Using the generator function
gen = simple_generator()
print(next(gen))  # Outputs 1
print(next(gen))  # Outputs 2
print(next(gen))  # Outputs 3

Comparison with regular functions:

Characteristic Regular function Generator function
Return return yield
Termination After the first return After each yield (until next request)
Return type Single value Iterator
State Not preserved Preserved
Memory Can load all data Generate on demand
What is a generator function? — Python - sobes.tech