Python yield keyword

python yield keyword

The Python yield keyword is used to control the program flow in a generator function.

Generators are functions that produce a sequence of values over time, rather than computing them all at once and storing them in memory.

They are memory-efficient and handy when dealing with large datasets or infinite sequences.

The yield keyword is at the heart of generators, as it enables the suspension and resumption of function execution.

Let’s dive into examples to see the yield keyword in action.

Example 1: Simple Generator Function

def count_up_to(n):
    i = 0
    while i <= n:
        yield i
        i += 1

In this example, the count_up_to function is a generator function that yields numbers from 0 up to a given value n.

Each time the yield statement is encountered, the function’s execution is paused, and the current value of i is yielded.

The generator can iterate over the numbers using a loop or other iterable constructs.

Example 2: Infinite Generator

def infinite_sequence():
    num = 0
    while True:
        yield num
        num += 1

Here, the infinite_sequence generator function generates an infinite sequence of numbers starting from 0.

By utilizing the yield keyword, we can obtain the numbers on-demand, without needing to compute and store the entire sequence in memory.

Example 3: Coroutine with ‘yield’ and ‘await’

async def greet(name):
    print("Starting the coroutine")
    await asyncio.sleep(1)
    yield f"Hello, {name}!"
    print("Ending the coroutine")

greeting = greet("Alice")

print(next(greeting))

This example demonstrates a coroutine that uses both the yield and await keywords.

The greet coroutine greets a given name after waiting for 1 second using the await asyncio.sleep(1) statement.

The yield statement returns the greeting message.

When calling next(greeting), the coroutine executes until it reaches the yield statement, returning the greeting and pausing its execution.

Conclusion

Python’s yield keyword unlocks the power of generators, enabling efficient lazy evaluation and the creation of iterable objects.

By leveraging the yield you can write memory-efficient code and handle large datasets or infinite sequences seamlessly.


Leave a Reply

Your email address will not be published. Required fields are marked *