Home Backend Development Python Tutorial Introduction to the usage of yield in python (with code)

Introduction to the usage of yield in python (with code)

Feb 22, 2019 pm 02:49 PM
python

This article brings you an introduction to the usage of yield in WeChat applet python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, if you don’t have a preliminary understanding of yield, then you first think of yield as “return”. This is intuitive. It is first of all a return. What does ordinary return mean? A certain value is returned in the program. After returning, the program will no longer run. After seeing it as return, think of it as part of a generator (the function with yield is the real iterator). Well, if you don't understand these, then treat yield as return first. Then look directly at the following program, and you will understand the full meaning of yield:

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(next(g))
Copy after login

Just a few lines of code will let you understand what yield is. The output of the code is this:

starting...
4
********************
res: None
4
Copy after login

I directly explain the code running sequence, which is equivalent to single-step debugging of the code:

1. After the program starts executing, because there is the yield keyword in the foo function, the foo function will not actually be executed. Instead, first get a generator g (equivalent to an object)

2. Until the next method is called, the foo function officially begins to execute. First execute the print method in the foo function, and then enter the while loop

3. The program encounters the yield keyword, and then thinks of yield as return. After returning a 4, the program stops and does not perform the assignment to res operation. At this time, the execution of the next(g) statement is completed, so the first part of the output The two lines (the first is the result of print above while, the second is the result of return) are the results of executing print(next(g)),

4. The program executes print(""20), output 20 *

5. Start executing the following print(next(g)) again. This time it is similar to the one above, but the difference is that this time it starts from just now The execution of the next program starts from where it stopped, that is, the assignment operation of res is to be performed. At this time, it should be noted that there is no value on the right side of the assignment operation at this time (because the return just went out, and there is no value on the left side of the assignment operation. Pass parameters), so at this time the res assignment is None, so the following output is res:None,

6. The program will continue to execute in the while, and encounter yield again. At this time, it also returns 4 , then the program stops, and the 4 output by the print function is the 4 output by this return.

At this point you may understand the relationship and difference between yield and return. The function with yield is a generator, not A function. This generator has a function which is the next function. Next is equivalent to which number is generated in the "next step". This time, the starting point of next is executed from the place where the last next stopped, so when calling next , the generator will not execute from the beginning of the foo function, it will just start where the previous step stopped, and then after encountering yield, return the number to be generated, and this step will end.

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)
g = foo()
print(next(g))
print("*"*20)
print(g.send(7))
Copy after login

Let’s look at another example of the send function of this generator. This example replaces the last line of the above example, and the output result is:

starting...
4
********************
res: 7
4
Copy after login

Let’s briefly talk about the send function. Concept: At this time, you should notice the purple words above, and why the value of res above is None, and this one becomes 7. Why? This is because send sends a parameter to res, because the above Speaking of, when returning, 4 is not assigned to res. The next time it is executed, it has to continue to perform the assignment operation and has to assign the value to None. If send is used, when the execution starts, it will continue from the previous time (return 4 After) execution, first assign 7 to res, then execute the function of next, meet the next yield, and end after returning the result.

5. The program executes g.send(7), and the program will continue to run downward from the yield keyword line, and send will assign the value 7 to the res variable

6. Because send The method contains the next() method, so the program will continue to run downwards to execute the print method, and then enter the while loop again

7. After the program execution encounters the yield keyword again, yield will return the subsequent value, the program Pause again until the next method or send method is called again.

That’s it. Let’s talk about why we use this generator. It’s because if we use List, it will take up more space. For example, take 0,1,2,3,4,5,6. ............1000

You may look like this:

for n in range(1000):
    a=n
Copy after login

At this time, range(1000) will generate a list containing 1000 numbers by default, so It takes up a lot of memory.

At this time, you can use the yield combination just now to form a generator for implementation, or you can use the xrange(1000) generator to implement

yield combination:

def foo(num):
    print("starting...")
    while num<10:
        num=num+1
        yield num
for n in foo(0):
    print(n)
Copy after login

Output:

starting...
1
2
3
4
5
6
7
8
9
10
Copy after login

xrange(1000):

for n in xrange(1000):
    a=n
Copy after login

It should be noted that there is no xrange() in python3. In python3, range() is xrange(). You can use python3 Check the type of range() in . It is already a instead of a list. After all, this needs to be optimized.

The above is the detailed content of Introduction to the usage of yield in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

See all articles