Sobes.tech
Junior — Middle

Can you explain what a generator function is and how it is used?

sobes.tech AI

Answer from AI

A generator function is a special type of function that can pause its execution and return intermediate values using the yield keyword. Unlike regular functions, generators allow iteration over a sequence of values without the need to create the entire list in memory at once.

Example in Python:

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

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

Here, the count_up_to function returns numbers from 1 to 5 one at a time. This is useful for working with large or infinite sequences, saving memory and allowing data to be processed as needed.

Can you explain what a generator function is and how… - sobes.tech