search
HomeTechnology peripheralsIt IndustryQuick Tip: Understanding the Yield Keyword in Python

Quick Tip: Understanding the Yield Keyword in Python

Quick Tip: Understanding the Yield Keyword in Python

Thanks to Shaumik Daityari for kindly helping to peer review this article.

When we call a function in Python, the function will normally start working until it encounters a return, exception, or reaches its end – after which it returns control back to the caller. Whenever you call that function again, the process will start from scratch!

Say that you asked a person to track the red cars on the road. The person will keep getting a question asking them if they spotted a red car or not, and the person in turn would answer with either ‘yes’ or ‘no’. If the person answered ‘yes’, the number of times the red car was spotted will increase.

Let’s see how we can do this in Python:

import time

def red_cars(answer):
    n = 0
    while True:
        if answer == 'yes':
            n = n + 1
            return n
        else:
            return n

stop = time.time() + 5 * 60
while time.time() 

<p>If you run the program, what do you notice? Did you notice that the number of times for the ‘yes’ answer is always capped at 1, and when you answer ‘no’ the number of times gets 0 regardless of answering ‘yes’ before?</p>

<p>Here is where Python’s yield keyword comes into play. yield is a means by which we <em>temporarily</em> hand control to the caller, and expect to continue from the point at which control has been handed over.</p>

<p>Before giving the solution to the above example, let me demonstrate a very simple example to better illustrate how yield works.</p>

<p>Say we have the following simple Python script:</p>


<pre class="brush:php;toolbar:false">def step_by_step():
    return 'step 1'
    return 'step 2'
    return 'step 3'
    
step = step_by_step()
for i in range (3):
    print step

If you run the script, you will get the following output:

step 1
step 1
step 1

Now, if we use yield instead, as follows:

def step_by_step():
    yield 'step 1'
    yield 'step 2'
    yield 'step 3'
    
step = step_by_step()
for i in range (3):
    print step.next()

The output would be as follows:

step 1
step 2
step 3

As you can see, we were able to create a series of values, as for each call the function continues from the point where it yields a value. This type of function is called a generator. Such function creates a generator iterator, as with each call to the method next() we move to the next yield statement.

If we come back to our main example (red cars), it can be written as follows to perform the required task:

import time

def red_cars(answer = None):
    n = 0
    while True:
        if answer=="yes":
            n = n + 1
            answer = yield n
        else:
            answer = yield n

car_color = red_cars()
car_color.next()

stop = time.time() + 5 * 60
while time.time() 

<p>Thus, as we can see, yield is deemed important when we are interested in resuming execution at the last point where the function (generator) exited, and where we are also interested in keeping the values of local variables between the different calls – unlike normal functions, where such values are destroyed when exiting the function.</p>

<p>There are, however, other uses of yield. For instance, you can use yield if you have a function which returns a sequence (for example, rows in an excel sheet) and you need to iterate over the sequence without having each value in memory at once. That is, to save memory. </p><p>yield can also be used when working with iterables, where we have a large list that is difficult to pass between functions. For instance, Python’s inbuilt functions for permutations and combinations in the itertools module use yield.</p>




<h2 id="Frequently-Asked-Questions-FAQs-about-the-Yield-Keyword-in-Python">Frequently Asked Questions (FAQs) about the Yield Keyword in Python</h2>



<h3 id="What-is-the-difference-between-the-yield-and-return-keywords-in-Python">What is the difference between the yield and return keywords in Python?</h3> <p>The yield and return keywords in Python are used in functions, but they serve different purposes. The return keyword is used when you want a function to produce a value and then terminate. Once a function returns a value, it is done executing and control is passed back to the caller. On the other hand, the yield keyword is used in a function like a return statement, but it produces a value and suspends the function’s execution. The function can be resumed later on from where it left off, allowing it to produce a series of values over time, instead of computing them all at once and sending them back like a list.</p>  <h3 id="How-does-the-yield-keyword-work-in-Python">How does the yield keyword work in Python?</h3> <p>The yield keyword in Python is used in a function with a loop to create an iterator. When the function is called, it returns an iterator, but does not start execution immediately. When the iterator’s next() method is called, the function starts executing. Once it encounters the yield keyword, it returns the argument passed to yield and pauses execution. The function can be resumed from where it left off by calling next() again, allowing the function to produce a series of values over time, behaving as a generator.</p>  <h3 id="Can-you-provide-an-example-of-using-the-yield-keyword-in-Python">Can you provide an example of using the yield keyword in Python?</h3> <p>Sure, here’s a simple example of using the yield keyword in Python:<br><br>def simple_generator():<br> yield 1<br> yield 2<br> yield 3<br><br>for value in simple_generator():<br> print(value)<br><br>In this example, simple_generator is a generator function because it uses the yield keyword. When we iterate over the generator object returned by simple_generator(), it yields 1, then 2, then 3, pausing its execution between each yield.</p>  <h3 id="What-are-the-benefits-of-using-the-yield-keyword-in-Python">What are the benefits of using the yield keyword in Python?</h3> <p>The yield keyword in Python allows you to write functions that can produce a sequence of results over time, rather than computing them all at once and returning them in a list for example. This can be particularly useful when the result set is large and you want to save memory. It also allows you to create your own iterable objects and use them with Python’s for loops, comprehensions, and other functions that expect an iterable.</p><h3 id="Can-a-function-contain-both-yield-and-return-statements-in-Python">Can a function contain both yield and return statements in Python?</h3> <p>Yes, a function in Python can contain both yield and return statements. However, it’s important to note that once a return statement is executed, the function’s execution is terminated, and control is passed back to the caller. So if a return statement is executed before a yield statement, the yield statement will never be reached. Conversely, if a yield statement is executed first, the function will be paused and control will be passed back to the caller, but the function can be resumed later on, at which point the return statement can be executed.</p>  <h3 id="Can-I-use-the-yield-keyword-in-a-recursive-function-in-Python">Can I use the yield keyword in a recursive function in Python?</h3> <p>Yes, you can use the yield keyword in a recursive function in Python. However, you need to remember to iterate over the recursive call and yield each value, otherwise you’ll get a generator object instead of the values you expect.</p>  <h3 id="What-is-the-difference-between-a-generator-function-and-a-normal-function-in-Python">What is the difference between a generator function and a normal function in Python?</h3> <p>The main difference between a generator function and a normal function in Python is that a generator function uses the yield keyword and a normal function uses the return keyword. When a generator function is called, it returns a generator object without even beginning execution of the function. When the next() method is called for the first time, the function starts executing until it reaches the yield keyword, which produces a value. The function then pauses execution and control is passed back to the caller. On the other hand, when a normal function is called, it starts execution immediately and runs to completion, returning a value.</p>  <h3 id="Can-I-use-multiple-yield-statements-in-a-single-function-in-Python">Can I use multiple yield statements in a single function in Python?</h3> <p>Yes, you can use multiple yield statements in a single function in Python. When the function is called, it will yield a value each time it encounters a yield statement, pausing its execution and passing control back to the caller. The next time the function’s next() method is called, it will resume execution from where it left off and run until it encounters the next yield statement.</p>  <h3 id="How-can-I-catch-the-StopIteration-exception-raised-by-a-generator-function-in-Python">How can I catch the StopIteration exception raised by a generator function in Python?</h3> <p>When a generator function in Python has no more values to yield, it raises a StopIteration exception. You can catch this exception by using a try/except block. Here’s an example:<br><br>def simple_generator():<br> yield 1<br> yield 2<br> yield 3<br><br>gen = simple_generator()<br><br>while True:<br> try:<br> print(next(gen))<br> except StopIteration:<br> break<br><br>In this example, we catch the StopIteration exception and break out of the loop when there are no more values to yield.</p><h3 id="Can-I-use-the-yield-keyword-in-a-lambda-function-in-Python">Can I use the yield keyword in a lambda function in Python?</h3> <p>No, you cannot use the yield keyword in a lambda function in Python. This is because lambda functions are limited to a single expression, and the yield keyword introduces a statement context. If you need to create a generator function, you’ll need to use a def statement to define a normal function.</p>

The above is the detailed content of Quick Tip: Understanding the Yield Keyword in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Behind the first Android access to DeepSeek: Seeing the power of womenBehind the first Android access to DeepSeek: Seeing the power of womenMar 12, 2025 pm 12:27 PM

The rise of Chinese women's tech power in the field of AI: The story behind Honor's collaboration with DeepSeek women's contribution to the field of technology is becoming increasingly significant. Data from the Ministry of Science and Technology of China shows that the number of female science and technology workers is huge and shows unique social value sensitivity in the development of AI algorithms. This article will focus on Honor mobile phones and explore the strength of the female team behind it being the first to connect to the DeepSeek big model, showing how they can promote technological progress and reshape the value coordinate system of technological development. On February 8, 2024, Honor officially launched the DeepSeek-R1 full-blood version big model, becoming the first manufacturer in the Android camp to connect to DeepSeek, arousing enthusiastic response from users. Behind this success, female team members are making product decisions, technical breakthroughs and users

DeepSeek's 'amazing' profit: the theoretical profit margin is as high as 545%!DeepSeek's 'amazing' profit: the theoretical profit margin is as high as 545%!Mar 12, 2025 pm 12:21 PM

DeepSeek released a technical article on Zhihu, introducing its DeepSeek-V3/R1 inference system in detail, and disclosed key financial data for the first time, which attracted industry attention. The article shows that the system's daily cost profit margin is as high as 545%, setting a new high in global AI big model profit. DeepSeek's low-cost strategy gives it an advantage in market competition. The cost of its model training is only 1%-5% of similar products, and the cost of V3 model training is only US$5.576 million, far lower than that of its competitors. Meanwhile, R1's API pricing is only 1/7 to 1/2 of OpenAIo3-mini. These data prove the commercial feasibility of the DeepSeek technology route and also establish the efficient profitability of AI models.

Midea launches its first DeepSeek air conditioner: AI voice interaction can achieve 400,000 commands!Midea launches its first DeepSeek air conditioner: AI voice interaction can achieve 400,000 commands!Mar 12, 2025 pm 12:18 PM

Midea will soon release its first air conditioner equipped with a DeepSeek big model - Midea fresh and clean air machine T6. The press conference is scheduled to be held at 1:30 pm on March 1. This air conditioner is equipped with an advanced air intelligent driving system, which can intelligently adjust parameters such as temperature, humidity and wind speed according to the environment. More importantly, it integrates the DeepSeek big model and supports more than 400,000 AI voice commands. Midea's move has caused heated discussions in the industry, and is particularly concerned about the significance of combining white goods and large models. Unlike the simple temperature settings of traditional air conditioners, Midea fresh and clean air machine T6 can understand more complex and vague instructions and intelligently adjust humidity according to the home environment, significantly improving the user experience.

Top 10 Best Free Backlink Checker Tools in 2025Top 10 Best Free Backlink Checker Tools in 2025Mar 21, 2025 am 08:28 AM

Website construction is just the first step: the importance of SEO and backlinks Building a website is just the first step to converting it into a valuable marketing asset. You need to do SEO optimization to improve the visibility of your website in search engines and attract potential customers. Backlinks are the key to improving your website rankings, and it shows Google and other search engines the authority and credibility of your website. Not all backlinks are beneficial: Identify and avoid harmful links Not all backlinks are beneficial. Harmful links can harm your ranking. Excellent free backlink checking tool monitors the source of links to your website and reminds you of harmful links. In addition, you can also analyze your competitors’ link strategies and learn from them. Free backlink checking tool: Your SEO intelligence officer

Another national product from Baidu is connected to DeepSeek. Is it open or follow the trend?Another national product from Baidu is connected to DeepSeek. Is it open or follow the trend?Mar 12, 2025 pm 01:48 PM

DeepSeek-R1 empowers Baidu Library and Netdisk: The perfect integration of deep thinking and action has quickly integrated into many platforms in just one month. With its bold strategic layout, Baidu integrates DeepSeek as a third-party model partner and integrates it into its ecosystem, which marks a major progress in its "big model search" ecological strategy. Baidu Search and Wenxin Intelligent Intelligent Platform are the first to connect to the deep search functions of DeepSeek and Wenxin big models, providing users with a free AI search experience. At the same time, the classic slogan of "You will know when you go to Baidu", and the new version of Baidu APP also integrates the capabilities of Wenxin's big model and DeepSeek, launching "AI search" and "wide network information refinement"

Building a Network Vulnerability Scanner with GoBuilding a Network Vulnerability Scanner with GoApr 01, 2025 am 08:27 AM

This Go-based network vulnerability scanner efficiently identifies potential security weaknesses. It leverages Go's concurrency features for speed and includes service detection and vulnerability matching. Let's explore its capabilities and ethical

Prompt Engineering for Web DevelopmentPrompt Engineering for Web DevelopmentMar 09, 2025 am 08:27 AM

AI Prompt Engineering for Code Generation: A Developer's Guide The landscape of code development is poised for a significant shift. Mastering Large Language Models (LLMs) and prompt engineering will be crucial for developers in the coming years. Th

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment