David's Blog

Yield Functions in Python

By David Li on Fri, 21 September 2024

In Python, you can use the yield function to create generators.

A generator is a type of iterator that can be used to generate a sequence of values on the fly. Generators are useful for working with large datasets or infinite sequences, as they allow you to generate values one at a time, rather than storing all of the values in memory at once.

Here is an example of a generator function that uses the yield function:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

In this example, we define a generator function called countdown that takes one parameter called n. Inside the function, we use a while loop to generate a sequence of values from n down to 1. Each time through the loop, we use the yield keyword to send the current value back as the next value in the sequence.

Here is an example of how to use the countdown generator:

for i in countdown(5):

In this example, we use a for loop to iterate over the values generated by the countdown generator. Each time through the loop, the next value in the sequence is generated by the yield keyword and printed to the console.

The output of this program would be:


By using the yield function, you can create generators that generate sequences of values on the fly,

© Copyright 2024 by FriendlyUsers Tech Blog. Built with ♥ by FriendlyUser. Last updated on 2024-07-22.