What Does the yield Keyword Do in Python? What Does the yield Keyword Do in Python?

Python is a versatile programming language that offers a wide range of features to simplify code development. One such feature is the "yield" keyword, which allows the creation of generator functions. Generator functions in Python are special functions that can pause and resume their execution, producing a sequence of values over time. In this article, we will explore what the "yield" keyword does and how it can be used effectively in Python.


Understanding Generators:

Before diving into the "yield" keyword, let's first understand what generators are. A generator is a type of iterable, similar to a list or a tuple, but with a significant difference. While a list or tuple holds all its values in memory at once, a generator generates values on the fly as requested, which can save memory and improve performance in certain situations.

A generator function is defined like a regular function, but instead of using the "return" keyword to return a value, it uses the "yield" keyword. When a generator function is called, it returns an iterator object, which can be used to iterate over the values generated by the function.

Using the "yield" Keyword:

The "yield" keyword plays a crucial role in generator functions. It allows the function to produce a value and pause its execution, preserving its internal state. The generator function can then be resumed from where it left off, continuing its execution and generating the next value.

Here's a simple example to demonstrate the usage of the "yield" keyword:


def count_up_to(n):
i = 0
while i <= n:
        yield i
        i += 1
# Using the generator function
counter = count_up_to(5)
# Iterating over the generated values
for num in counter:
    print(num)

In the above code, the `count_up_to` function is a generator function that yields values from 0 up to `n`. The function uses a `while` loop to generate the values and the `yield` keyword to produce each value. When the loop encounters the `yield` statement, it pauses and yields the current value. The loop continues from where it left off in the next iteration, thanks to the state preserved by the generator.

The `counter` object is an iterator returned by the `count_up_to` function. By iterating over the `counter` object using a `for` loop, we can print each generated value.

Generator functions provide a powerful way to generate sequences of values dynamically without the need to store them all in memory at once. This can be especially useful when dealing with large datasets or infinite sequences.

Advanced Usage of "yield":

The "yield" keyword is not only limited to producing values. It can also be used to receive values from the caller while the generator is running. This is achieved by assigning a value to the result of the `yield` expression.

Consider the following example:


def accumulate():
total = 0
while True:
value = yield total
total += value
# Using the generator function
accumulator = accumulate()
# Starting the generator
next(accumulator)
# Sending values to the generator
print(accumulator.send(2))   # Output: 2
print(accumulator.send(5))   # Output: 7
print(accumulator.send(10))  # Output: 17

In this code, the `accumulate` function is a generator that continuously accumulates values. The `yield` statement is used to produce the current total value while also accepting a new value from the caller. The `yield` expression acts as both a producer and a consumer.

To start the generator, we call `next(accumulator)` once to advance it to the first `yield` statement. Then, we can send values to the generator using the `send()` method, which assigns the sent value to the `yield` expression and resumes the generator's execution.

The "yield" keyword in Python plays a fundamental role in defining generator functions. It allows functions to produce a sequence of values over time, pausing and resuming their execution as needed. Generator functions offer an efficient and memory-friendly way to work with large datasets or infinite sequences. By understanding and utilizing the "yield" keyword, Python developers can write elegant and effective code that takes advantage of generator-based programming paradigms.

Published on May 26, 2023

Tags: Python | yield

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.