When to use yield instead of return in Python? - GeeksforGeeks (2024)

Skip to content

When to use yield instead of return in Python? - GeeksforGeeks (1)

Last Updated : 08 Sep, 2022

Improve

Improve

Like Article

Like

Save

Report

The yield statement suspends a function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.

Let’s see with an example:

Python

# A Simple Python program to demonstrate working

# of yield

# A generator function that yields 1 for the first time,

# 2 second time and 3 third time

def simpleGeneratorFun():

yield 1

yield 2

yield 3

# Driver code to check above generator function

for value in simpleGeneratorFun():

print(value)

Output:

123

Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory. Yield is used in Python generators. A generator function is defined just like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

Python

# A Python program to generate squares from 1

# to 100 using yield and therefore generator

# An infinite generator function that prints

# next square number. It starts with 1

def nextSquare():

i = 1

# An Infinite loop to generate squares

while True:

yield i*i

i += 1 # Next execution resumes

# from this point

# Driver code to test above generator

# function

for num in nextSquare():

if num > 100:

break

print(num)

Output:

149162536496481100


When to use yield instead of return in Python? - GeeksforGeeks (2)

GeeksforGeeks

Improve

Please Login to comment...

Similar Reads

Difference between Yield and Return in Python

Python Yield It is generally used to convert a regular Python function into a generator. A generator is a special function in Python that returns a generator object to the caller. Since it stores the local variable states, hence overhead of memory allocation is controlled. Example: # Python3 code to demonstrate yield keyword # Use of yield def prin

2 min read

Python Yield And Return In Same Function

Python, a versatile and powerful programming language, offers developers various tools and features to enhance code readability and efficiency. One such feature is the combination of yield and return statements within the same function. In this article, we will explore some commonly used methods where these two statements work together, providing a

3 min read

How to Use Yield Keyword for Memory Efficient Python Code

We are given a task to understand how to use the yield keyword for memory-efficient Python code with the help of different examples with their code. In this article, we will see how to use the yield keyword for memory-efficient Python code. What is the Yield Keyword?The yield keyword in Python is used in the context of generator functions and is fu

4 min read

How to Use __call__() Method Instead of __new__() of a Metaclass in Python?

In Python, metaclasses provide a way to customize class creation. The __new__ and __init__ methods are commonly used in metaclasses, but there's another powerful tool at your disposal: the __call__ method. While __new__ is responsible for creating a new instance of a class, __call__ allows you to control what happens when an instance is called as a

3 min read

Python | yield Keyword

In this article, we will cover the yield keyword in Python. Before starting, let's understand the yield keyword definition. Syntax of the Yield Keyword in Python def gen_func(x): for i in range(x): yield iWhat does the Yield Keyword do? yield keyword is used to create a generator function. A type of function that is memory efficient and can be used

4 min read

Python Yield Multiple Values

In Python, yield is a keyword that plays a very crucial role in the creation of a generator. It is an efficient way to work with a sequence of values. It is a powerful and memory-efficient way of dealing with large values. Unlike a return statement which terminates the function after returning a value, yield produces and passes a series of values.

4 min read

How to Yield Values from List in Python

The yield keyword in Python produces a series of values one at a time and is used with the generator function, it works the same as the return keyword the difference being that the yield keyword produces a sequence of values one at a time. In this article, we will explore different approaches to yield values from a list in Python. Yield Values from

2 min read

Use jsonify() instead of json.dumps() in Flask

Here, we will understand the jsonify() function in the Flask web framework for Python that converts the output of a function to a JSON response object. It is similar to the json.dumps() function in the Python standard library, which converts a Python object to a JSON-formatted string. What is jsonify() The jsonify() function is useful in Flask apps

4 min read

The yield Keyword in Ruby

We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with

2 min read

Scala | yield Keyword

yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn't work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over

2 min read

Article Tags :

Practice Tags :

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

When to use yield instead of return in Python? - GeeksforGeeks (3)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); jQuery('.suggest-bottom-btn').on('click', function(){ var suggest_val = $.trim($("#suggestion-section-textarea").val()); var error_msg = false; if(suggest_val != ""){ if(suggest_val.length <= 2000){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify({ "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

` }), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').html("Sent "); setTimeout(() => { jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); }, 1000); }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('#suggestion-modal-alert').html("Character limit exceeded."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('#suggestion-modal-alert').html("Enter valid input."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } }) $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

When to use yield instead of return in Python? - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6301

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.