• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Difference between yield and return in Python

Difference between yield and return in Python

Author: Aditya Raj
Last Updated: September 22, 2021

You might have used yield and return statements while programming in python. In this article, we will discuss the theoretical concepts of return and yield keywords. We will also look at the difference between working of yield and return statements in python.

Table of Contents
  1. What is yield and return in Python?
  2. The return keyword
  3. The yield keyword 
  4. Difference between yield and return 
  5. Conclusion

What is yield and return in Python?

Yield and return are keywords in python. They are used in a function to pass values from one function to another in a program.

The return keyword

The return statements are used in a function to return objects to the caller function. We can return a single value like a number or string or a container object such as a python dictionary, a tuple, or a list. 

For example, the sumOfNums()  function returns a number to the caller in the following source code.

def sumOfNums(num1, num2):
    result = num2 + num1
    return result


output = sumOfNums(10, 20)
print("Sum of 10 and 20 is:", output)

Output:

Sum of 10 and 20 is: 30

Similarly, we can use return statements to return container objects as shown in the following example. Here the function “square” takes a list of numbers as input and returns a list of squares of the elements of the input list.

def square(list1):
    newList = list()
    for i in list1:
        newList.append(i * i)
    return newList


input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output list is:", output)

Output:

input list is: [1, 2, 3, 4, 5, 6]
Output list is: [1, 4, 9, 16, 25, 36]

We can have more than one return statement in a function. However, once a return statement is executed in the program, the statements written after the return statement will never be executed. 

The yield keyword 

The yield statements are also used in a function to return values to the caller function. But the yield statement works in a different way. When the yield statement is executed in a function, it returns a generator object to the caller. The value in the generator object can be accessed using the next() function or a for loop as follows.

def square(list1):
    newList = list()
    for i in list1:
        newList.append(i * i)
    yield newList


input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output from the generator is:", output)
print("Elements in the generator are:",next(output))

Output:

input list is: [1, 2, 3, 4, 5, 6]
Output from the generator is: <generator object square at 0x7fa59b674a50>
Elements in the generator are: [1, 4, 9, 16, 25, 36]

A function can have more than one yield statement. When the first yield statement is executed, it pauses the execution of the function and returns a generator to the caller function. When we perform the next operation on a generator using the next() function, the function again resumes and executes till the next yield statement. This process can be continued till the last statement of the function. You can understand this using the following example.

def square(list1):
    yield list1[0]**2
    yield list1[1] ** 2
    yield list1[2] ** 2
    yield list1[3] ** 2
    yield list1[4] ** 2
    yield list1[5] ** 2


input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output from the generator is:", output)
print("Elements in the generator are:")
for i in output:
    print(i)

Output:

input list is: [1, 2, 3, 4, 5, 6]
Output from the generator is: <generator object square at 0x7fa421848a50>
Elements in the generator are:
1
4
9
16
25
36

You should keep in mind that when the generator is passed to the next() function after execution of the last yield statement, it causes StopIteration error. It can be avoided by using the next() function in a python try except block.

Difference between yield and return 

There are two major differences between the working of yield and return statements in python.

  •  Return statement stops the execution of the function. Whereas, yield statement only pauses the execution of the function.
  • The statements written in a program after the return statement are unreachable and are never executed. On the other hand, statements written after the yield statement are executed when the function resumes its execution.

Conclusion

In this article, we have studied yield and return statements in Python. We also looked at the difference between yield and return statement. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us