TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: When to Prefer Yield Over Return in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

When to Prefer Yield Over Return in Python

Last updated: Nov 05, 2023 12:09 am
By Meenakshi Agarwal
Share
4 Min Read
Python program-When to Prefer Yield Over Return
Python program-When to Prefer Yield Over Return
SHARE

Let’s check out when do we prefer Yield over Return in Python. The former is used by the generator function to create an iterator. And the latter is a general-purpose statement to return a value from a regular function.

Contents
Need an Iterator Not a Single ValueNeed to Generate a Large List

The return is a control statement in Python which declares the end of a function execution by returning some value to its caller. At the same time, every function clears its local stack usage such as variables or its attributes.

Also, it does not maintain any state as the return call marks its execution as completed. Hence, any further instance of the same method starts from its very first line of code.

When to Prefer Yield Over Return

Need an Iterator Not a Single Value

At times, we need a function to pause instead of merely returning a value instantly. Also, the requirement is to execute it on a recurring basis and resume execution from the point of pause.

The yield statement allows us to halt a function execution, return a value, and preserves the current state, which is enough for continuing from the same point later on further request.

# Python program to Illustrate Usage of Yield 

# gen_func() yields 1 in the first call
# 2 in the second, and 3 during the third.
def gen_func(): 
    yield 1
    yield 2
    yield 3

# Test code to test our generator function 
for var in gen_func(): 
    print(var)

The above code gives the following output upon execution.

1
2
3

Need to Generate a Large List

Let’s bring more clarity on using yield instead of return.

The return statement transfers the output (a sequence, a string or a number, etc.) of a function to its caller all in one go. On the contrary, a yield can send back a sequence of values, one at a time in a step by step manner.

We should prefer yield when we want to traverse a large sequence, but don’t want to keep it in memory.

Yield turns a function into a Python generator. It has a function-like syntax, but whenever it requires to generate a value, it calls yield instead of the return.

If a Python function definition includes a yield call, then it automatically transforms into a generator function.

# Python program to produce cubes from 1 
# to 1000 using a generator function
  
# Let's have a infinite generator function
def nextCube(): 
    ii = 1; 
  
    # This loop runs endlessly  
    while True: 
        yield ii*ii*ii
        ii += 1  # Next execution resumes  
                 # from this point      
  
# Driver code to test our generator
for var in nextCube(): 
    if var > 1000: 
         break    
    print(var)

Executing the above code produces the following result.

1
8
27
64
125
216
343
512
729
1000

We hope that after reading this post, you are clear about when to prefer Yield over Return. However, to learn more Python stuff, do read our step by step Python tutorial.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Generator Function, Expression with Examples Python Generator Tutorial
Next Article Introduction to C Programming using codeblocks Set up C Programming Environment using Code::Blocks

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x
x