What are Python generators and how do they work?

Python generators are functions that can be paused and resumed, allowing them to generate a sequence of values over time. They use the yield keyword to yield values one at a time instead of returning them all at once. Generators are memory-efficient as they generate values on-the-fly instead of storing them in memory. You can iterate over the values produced by a generator using a for loop or by explicitly calling the next() function. Generators are commonly used for efficient processing of large datasets and generating infinite sequences.

Code Example

def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Create a generator object
fibonacci = fibonacci_generator()

# Generate Fibonacci sequence up to a certain limit
limit = 200
sequence = []
for num in fibonacci:
    if num > limit:
        break
    sequence.append(num)

# Print the generated Fibonacci sequence
print(sequence)

In this example, we define a generator function called fibonacci_generator(). This function generates an infinite sequence of Fibonacci numbers using the yield keyword. It starts with two initial values, a and b, and in each iteration, it yields the current value of a and updates a and b to the next Fibonacci numbers.

We then create a generator object by calling fibonacci_generator(). This object can be iterated over to generate Fibonacci numbers on-the-fly.

Next, we define a limit for the Fibonacci sequence (limit = 200) and create an empty list called sequence to store the generated numbers.

We use a for loop to iterate over the fibonacci generator. Each number generated by the generator is checked against the limit. If the number exceeds the limit, we break out of the loop. Otherwise, we append the number to the sequence list.

Finally, we print the generated Fibonacci sequence.

Since the Fibonacci generator is implemented as a generator function, it generates Fibonacci numbers only when requested. This allows us to generate a sequence of Fibonacci numbers without the need to store the entire sequence in memory at once.