• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Python yield vs return Explained in Detail with Examples

Aniruddha Chaudhari/42387/8
CodePython

In the morning, I had a discussion with one of my colleagues and usually, it happens at coffee. And I asked him, “for my project, I need a function that returns series of numbers every time I make a call”.

And he suggested, “Why don’t you use yield instead of the return statement in generator function?”.

Just after the coffee, I started digging into it.

After having a good understanding, I thought of curating my search for Python yield vs return with detail examples. So that you can find complete detail in one post.

There is so much confusion about Python yield and return statement to bear.

Yield statement in the Python is used whenever you need to define generator function. You can not use yield statement outside of generator function.

When you use yield statement in any function, it turns it into a generator function.

Syntax

def generatorFunction():
    ----
    yield <return_value>;
    ----

To understand the yield statement in Python, you should know the generator function.

So let’ see…

What is Generator in Python?

How is generator function is different from a normal function?

As per the name “Generator”, is a function that generates the values (more than one or series of values). It behaves like an iterator.

How does generator different from iterators?

You can call generator function in the loop.

Simply, when you write yield statement in any function, it becomes generator function.

Generator functions are special types of iterates that iterate only once. It does not save any values in memory. It generates the values on the fly.

How do yield Statement and Generator work in Python?

The syntax of yield statement is similar to return statement but behaves differently.

  • Whenever yield statement occurs inside generator function, the program pauses the execution and return the value to the caller.
  • It retains the state of the function where it is paused.
  • Next time, when a caller calls the generator function, function body executes the statement from where it has been paused instead of executing the first statement.
  • You can call the generator function as long as it has not reached its last statement.

I know it is little difficult to understand by just reading. Let’s dive in the example to clear your understanding.

Python yield Examples with Generator Function:

1. Generating Number Series:

def simpleGeneratorFun():
    n =1
    yield n
    n = n+1
    yield n
    n=n+1
    yield n

for value in simpleGeneratorFun():
    print(value)

Output:

1 2 3

In the above program, we are literally calling the function simpleGeneratorFun() three times.

How does above code work?

  1. When you call function simpleGeneratorFun() the first time, line number 2 and 3 are executed.
  2. When you call the same function second time, it executes line number 4 and 5.
  3. For the third call, it executes lines of code from line 6 and 7.

2. Calling Generator Function using For Statement:

Above program, you can just fold it by using statementfor.

def simpleGeneratorFun():
    for i in range (1, 4):
        yield i

for value in simpleGeneratorFun():
    print(value)

Output:

1 2 3

3. Using next Statement:

You can also use next() statement for iteratively calling generator functions.

def simpleGeneratorFun():
    for i in range (1, 4):
        yield i

obj =  simpleGeneratorFun()

nValue = next(obj)
print nValue
nValue = next(obj)
print nValue
nValue = next(obj)
print nValue

Output:

1 2 3

If you call nValue = next(obj) one more time, it throws an exception as…

Traceback (most recent call last):
File "yield.py", line 13, in <module>
nValue = next(obj)
StopIteration

There are some drawbacks using next() over for loop.

You have to write next() for each call to generator function. If there are a huge number of calls to the generator function, it is tedious to call each time to next() statement.

The number of iteration required to complete execution of generator function is same as a number of yield statement into the generator function. If you are not aware of the number of yield statement in your function, it is convenient to use for loop instead of a statementnext().

4. Finding Sum of all generated values:

You can simply make the sum of all the values returned from generator function using the inbuiltsum() function.

def simpleGeneratorFun():
    n =3
    for i in range (1, 4):
        yield i

print "Sum of Series: ", sum(simpleGeneratorFun())

Output:

Sum of Series: 6

5. Generating Fibonacci Series using yield Statement:

Take this real-time use of yield statement to generate Fibonacci series.

def simpleGeneratorFun():
    pre1 = 1
    pre2 = 1
    sumValue = 1
    yield sumValue
    for i in range (0, 5):
        yield sumValue
        sumValue = pre1 + pre2
        pre1 = pre2
        pre2 = sumValue

for value in simpleGeneratorFun():
    print(value)

Output:

1 1 2 3 5

Python yield vs return statement:

What is the difference between yield and return statement in Python?

  • Return statement just returns the value to its caller. It does not preserve any state from last function call.
  • Whatever you write after the return statement does not execute. So you have to write return statement usually at the end of the function.
  • You can write yield functions anywhere in generator function. The code after the yield statement is executed in next function call.
  • Return statement does not retain any state. Every time you call function, it executed independently.
  • In yield, the function is executed from where it is paused in last function call.

When to use of Yield statement over return?

In Python, the return statement does not save any state and it simply returns value to the caller. When you need to produce a series of values for every time calling function, use yield statement.

Any point to discuss? Please let me know in the comment.

There are some related codes you can try running them.

  • List and Tuple (Difference Between Two)
  • Reverse String in Python using Extended Slice Syntax
  • Get all the Permutations of String

Happy Pythoning!

Python Interview Questions eBook

CodePython
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Nur Amin Aifat
    September 16, 2018 at 2:55 pm

    What kind of state have yield and why any state haven’t return statement?
    explain it again please… just state.

    • Reply
      Aniruddha Chaudhari
      September 18, 2018 at 8:36 am

      Nur,

      In case of return and normal function, every time when you call function, it executes the complete code inside the function.

      Whereas, in yield statement and generator, when you call the generator function, it executes the code inside the generator function from where it is left (does not execute the code complete). It saves the state.

      Check the Python program- 1. Generating Number Series:

      >> When you call function simpleGeneratorFun() the first time, line number 2 and 3 are executed.
      >> When you call the same function second time, it executes line number 4 and 5.
      >> For the third call, it executes lines of code from line 6 and 7.
  • Reply
    Nur Amin Aifat
    September 16, 2018 at 3:11 pm

    What is the meaning of, generates the values on the fly?

    • Reply
      Aniruddha Chaudhari
      September 18, 2018 at 8:18 am

      It means it does not save any values. And each value is generated every time when it is needed.

  • Reply
    Avira
    December 14, 2018 at 2:29 am

    Thanks for sharing and detail about this Python topic.

    • Reply
      Aniruddha Chaudhari
      December 14, 2018 at 9:19 am

      You’re welcome, Avira!

  • Reply
    Fernando
    May 20, 2020 at 2:31 am

    The best explanation that I have found. Thanks for taking the time to teach others.

    • Reply
      Aniruddha Chaudhari
      May 23, 2020 at 4:33 am

      Thanks, Fernando! And you’re welcome!

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard