Sobes.tech
Junior — Middle

Can you explain what a generator is in Python and how to use it?

sobes.tech AI

Answer from AI

A generator in Python is a function that returns an iterator and allows sequentially yielding values using the yield keyword. Unlike a regular function that returns all at once, a generator 'remembers' its state between calls and yields values one by one.

This is convenient for working with large amounts of data or infinite sequences, as the generator does not load all data into memory.

Example of a generator that yields 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)

Output:

0
1
2
3
4

Here, yield pauses the function execution, returning the current value, and resumes on the next call.