SoFunction
Updated on 2025-04-14

A post to quickly understand the yield keyword in python

Preface

Imagine you are making a cake, but the cake is very large. You don’t want to finish it all at once, but you want to make a little bit and eat a little bit.yield keywordsThat will allow you to do this.

(Insert, the most widely used meaning of yield itself is: production and yield, which can actually reflect its function)

1. The basic function of yield

In Python,yieldKeywords can turn our function into a "generator". The generator is like a special function that remembers which step you have done and then continues from where you stopped last time next time.

2. How to use yield

  • Turn a function into a generator: As long as you use it in the functionyield, this function is no longer an ordinary function, it becomes a generator.

  • Generate value: Each time the function is executed toyieldWhen it "produces" a value and then stops. Next time this generator is called, it will continue to execute from where it stopped last time.

  • Remember the status: When the generator stops, it remembers all variables and their states, so that the next time it starts, it can continue from where it last stopped.

3. A simple example

def count_to(max):
    count = 1
    while count <= max:
        yield count  # It's not over yet, but remember first, use yield to generate the value        count += 1   # continue
# Create a generatorcounter = count_to(5)

# Iterative generatorfor number in counter:
    print(number)

This code will output:

1
2
3
4
5

Each cycle,yieldA number will be generated, and the function will pause there. When the next loop starts, the function continues to execute from where it was last stopped.

Summarize

  • yieldLet the function become a generator.
  • The generator can generate one value at a time instead of all values ​​at once.
  • The generator will remember which step you have done and can continue next time from where you stopped last time.

This is all about this article about the yield keyword in python. For more information about yield keywords related to python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!