Skip to main content

Command Palette

Search for a command to run...

Generators in Python

Updated
1 min read
Generators in Python
D

"Passionate software developer with a focus on Python. Driven by a love for technology and a constant desire to explore and learn new skills. Constantly striving to push the limits and create innovative solutions.”

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():
    print(i)

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.

More from this blog

D

Deven's Blog

14 posts

Passionate software developer driven by a love for technology and a constant desire to explore and learn new skills. Constantly striving to push the limits and create innovative solutions.