Python Yield Multiple Values
Last Updated :
24 Apr, 2025
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. In this article, we are going to deal with various scenarios where yield can be found a good fit. We will be dealing with some known questions and how can be they solved with the use of the yield keyword.
Python Yield Multiple Values
Below, we are going to explore various examples of Python Yield Multiple Values. We are going to see different problems with yield keywords.
Python Yield Multiple Values with Simple List Parsing
In this example, the below code defines a generator function `listIter` that yields each element of a given list. In the main function, a list `[1,2,3,4,5]` is defined, and the generator is created by calling `listIter(l)`. The `for` loop iterates through the generator, printing each element of the list on the same line.
Python3
#generator Function
def listIter(l):
for i in l:
yield i
#main function
if __name__ == "__main__":
#defining a list
l= [1,2,3,4,5]
#function calling
gen = listIter(l)
for i in range(len(l)):
print(next(gen),end= " ")
Python Yield Multiple Values with Fibonacci Series
In this example, below code defines a generator function `fibo` to generate the Fibonacci series up to the nth term. It uses variables `a` and `b` as the first two elements, and `c` to calculate the next term. The generator yields each term one by one. In the main function, the generator is called with `n=20`, and the `for` loop prints the first 20 terms of the Fibonacci series.
Python3
#fibonacci function
def fibo(n):
# a,b are first two elements of fibonacci series
a,b,c,i = 0,1,1,0
#passing the first element to the main function
yield a
while i < n-1:
yield c
c = a+b
a=b
b=c
i += 1
#Main Function
if __name__ == "__main__":
n=20
#Function Calling
gen = fibo(n)
for i in range(n):
print(next(gen),end= " ")
Output0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Python Yield Multiple Values with Finding Factors
In this example, below code defines a generator function `factors` to find and yield the factors of a given number `n`. In the main function, with `n=20`, the generator is called using `list(factors(n))`, and the factors of 20 are printed using a `for` loop.
Python3
#factors function
def factors(n):
#finding factors
for i in range(1, n + 1):
if n % i == 0:
yield i
#main method
if __name__ == "__main__":
n=20
#function calling and displaying
for i in list(factors(n)):
print(i,end=" ")
Python Yield Multiple Values with Random Number Generator
In this example, below code utilizes the `random` module to generate a series of random numbers between 0 and 10 using the `randomNum` generator function. In the main function, with `n=5`, the generator is called using `list(randomNum(n))`, and a `for` loop prints five random numbers on a single line.
Python3
#importing random module
import random
#defining the generator function
def randomNum(n):
for i in range(n):
yield round(random.random()*10)
#main function
if __name__ == "__main__":
n=5
#calling the function
for i in list(randomNum(n)):
print(i,end=" ")
Conclusion
In Python, yield keyword in used in the creation of a generator. Unlike returns, it do not terminates a method rather it temporarily suspends the method. We can pass more than one value from a method to the main function or another method with the help of yield keyword. In this article we have covered use cases of yield keyword with some working examples along with their explanations.
Similar Reads
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
Python dictionary values()
values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
2 min read
Print Single and Multiple variable in Python
In Python, printing single and multiple variables refers to displaying the values stored in one or more variables using the print() function. Let's look at ways how we can print variables in Python: Printing a Single Variable in PythonThe simplest form of output is displaying the value of a single v
2 min read
Python - Multi-Line Statements
In this article, we are going to understand the concept of Multi-Line statements in the Python programming language. Statements in Python: In Python, a statement is a logical command that a Python interpreter can read and carry out. It might be an assignment statement or an expression in Python. Mul
3 min read
Taking multiple inputs from user in Python
While taking a single input from a user is straightforward using the input() function, many real world scenarios require the user to provide multiple pieces of data at once. This article will explore various ways to take multiple inputs from the user in Python. Using input() and split()One of the si
5 min read
How to check multiple variables against a value in Python?
Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python: Method #1: Using or operator This is pretty simple and straightforward. The following code snippets illustrate this method. Example
2 min read
Python | sympy.sets.open() method
With the help of sympy.sets.open() method, we can make a set of values by setting interval values like right open or left open that means a set has right open bracket and left open brackets by using sympy.sets.open() method. Syntax : sympy.sets.open(val1, val2) Return : Return set of values with rig
1 min read
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
7 min read
Python | Pandas DataFrame.values
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure o
2 min read
Python MCQ (Multiple Choice Questions) with Answers
Python is a free open-source, high-level and general-purpose with a simple and clean syntax which makes it easy for developers to learn Python. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Sof
3 min read