yield keyword in Python

In Python, yield is an important keyword, which is closely related to generator (Generator) and lazy evaluation (Lazy Evaluation).

yield allows a function to yield values during iteration without having to calculate them all at once. This feature is especially useful when working with large data sets or infinite sequences.

1. yieldKeyword

1.1 Basic concepts of yield

yield is a keyword used to define a generator function. Generator functions can be paused and resumed, allowing values to be generated one by one without calculating them all at once. When the generator function reaches the yield statement, it will generate a value, save its state, and then wait for the next call to continue execution.

1.2 How the generator works

Generators are a special type of iterator created by generator functions. A generator function contains at least one yield statement, which can return a value and continue execution from the yield statement on the next iteration. This allows the generator function’s state to remain unchanged while the values can be generated one by one.

Here is a simple generator function example:

def simple_generator():
    yield 1
    yield 2
    yield 3

gen = simple_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
print(next(gen)) # Output: 3

In the example, simple_generator is a generator function that contains three yield statements. When we create a generator object gen and call the next() function, the generator function continues execution from the yield statement after each call , and generate corresponding values.

2. Create a generator

2.1 Generator function

A generator function is a function containing a yield statement that produces a value. The execution of a generator function can be paused and resumed multiple times, producing a value each time it is paused.

Here is an example of a generator function that generates the Fibonacci sequence:

def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

gen = fibonacci_generator()
for _ in range(10):
    print(next(gen)) # Output the first 10 Fibonacci numbers

2.2 Generator expression

In addition to generator functions, Python also provides generator expressions, which are similar to list comprehensions but return a generator object that generates values one by one. The syntax of generator expressions is more compact.

The following is an example of a generator expression that generates the square of a natural number:

gen = (x**2 for x in range(1, 6))
for value in gen:
    print(value) # Output: 1 4 9 16 25

Generator expressions can generate values without creating additional functions and are suitable for simple iteration needs.

3. Advanced usage of yield

3.1 Generator state preservation

Generator functions maintain their state each time they are executed. This means it can be used to generate unlimited sequences or large data sets without having to store all the data in memory.

Here is an example of an infinitely increasing generator:

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

gen = infinite_increment()
for _ in range(5):
    print(next(gen)) # Output: 0 1 2 3 4

3.2 Generator data filtering

yield can be used in conjunction with conditions to filter the generated values. This allows the generator to only generate values that meet certain criteria.

Here is an example generator that generates even numbers:

def even_numbers():
    num = 0
    while True:
        if num % 2 == 0:
            yield num
        num + = 1

gen = even_numbers()
for _ in range(5):
    print(next(gen)) # Output: 0 2 4 6 8

3.3 Lazy calculation of generators

Lazy evaluation of generators is a way of computing values when needed, rather than computing them all at once. This is useful when working with large data sets or infinite sequences.

Here’s an example that generates the squares of natural numbers, but only counts the first 5:

def lazy_square(limit):
    for x in range(1, limit + 1):
        yield x**2

gen = lazy_square(5)
for value in gen:
    print(value) # Output: 1 4 9 16 25

Lazy computing allows saving memory and computing resources when processing large amounts of data.

Summary

Advanced uses of yield include state preservation of generators, allowing infinitely incrementing or decrementing generators. It can also be used in conjunction with conditions to filter the generated values to only generate values that meet certain conditions. Most importantly, yield supports lazy calculation, allowing values to be calculated when needed rather than all at once, thus saving memory and computing resources.

Yield is a powerful tool when working with large data sets, infinite sequences, or when values need to be generated one by one. By deeply understanding yield, you can make better use of generators and lazy calculations, improving the efficiency and maintainability of your code.


———————————END——————- ——–

Digression

In the current era of big data, how can one keep up with the times without mastering a programming language? Python, the hottest programming language at the moment, has a bright future! If you also want to keep up with the times and improve yourself, please take a look.

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.


CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

1. Learning routes in all directions of Python

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Python essential development tools

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.