Sobes.tech
Middle

What are generators in Python and what are they used for?

sobes.tech AI

Answer from AI

Generators in Python are special functions that allow iteration over a sequence of values without creating the entire sequence in memory at once. Instead of the return statement, generators use yield, which returns a value and pauses the function's execution, preserving its state for the next call.

Generators are useful for memory optimization and performance enhancement, especially when working with large datasets or infinite sequences, as they compute values on demand (lazy evaluation).

An example of a generator that returns numbers from 0 to n-1:

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

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

This approach saves memory because it does not need to store the entire list of numbers at once.