Generators in Python

Generators in Python


1 min read

Python generators are functions that generate an iterable sequence of values. Unlike regular functions, generators use the "yield" keyword instead of "return" to return a value and suspend the execution of the function. This allows generators to produce a sequence of values on the fly, rather than generating a complete list or tuple of values at once.

Here is an example of a simple generator that produces the first 5 even numbers:

def even_numbers():
    n = 0
    while n < 10:
        yield n
        n += 2

for i in even_numbers():

In this example, the even_numbers function uses a while loop to generate even numbers starting from 0 and incrementing by 2 until the value of n is 10. Instead of returning the value of n, the yield keyword is used to return the current value of n and suspend the execution of the function until the next value is requested. The for loop then iterates over the values produced by the generator and prints them to the console.

Generators can be used in many different scenarios, such as generating large amounts of data that would be too memory-intensive to generate all at once, or generating data on-the-fly in response to user input.