How to Yield Values from List in Python
Last Updated :
23 Feb, 2024
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 List in Python
Below are the possible approaches to Yield Values From a List In Python:
- Using Basic Generator
- Using itertools.repeat() Function
- Using a map with a generator function:
Yield Values From List Using Basic Generator
In the below approach code, the generatorFn() function is a basic generator that yields values from the data list. The yield statement is used to produce each value one at a time. The for loop is then used to iterate over the generated values and print them.
Python3
def generatorFn():
data = [ "Python" , "Java" , "C++" , "JavaScript" , "HTML" , "CSS" ]
for language in data:
yield language
for value in generatorFn():
print (value)
|
Output
Python
Java
C++
JavaScript
HTML
CSS
Yield Values From List Using itertools.repeat()
In the below approach code, it uses itertools.repeat to repeat the given list (data) a specified number of times (repeat_count), and yield from is used to yield each element, resulting in a single iteration through the repeated list. The repeat_count of 1 ensures a single iteration without an infinite loop.
Python3
from itertools import repeat
def yield_using_repeat(lst, repeat_count):
for item in repeat(lst, repeat_count):
yield from item
data = [ "Python" , "Java" , "C++" , "JavaScript" , "HTML" , "CSS" ]
repeat_count = 1
for language in yield_using_repeat(data, repeat_count):
print (language)
|
Output
Python
Java
C++
JavaScript
HTML
CSS
Yield Values From List Using a map With a Generator Function
In the below approach, yield_values_generator is a generator function that yields values from the input list. The map function is then used to apply the lambda function to each generator element, effectively yielding the values from the list. Finally, the for loop iterates through the result of the map and prints each language
Python3
def yield_values_generator(lst):
for item in lst:
yield item
data = [ "Python" , "Java" , "C++" , "JavaScript" , "HTML" , "CSS" ]
generator_result = map ( lambda x: x, yield_values_generator(data))
for language in generator_result:
print (language)
|
Output
Python
Java
C++
JavaScript
HTML
CSS
Share your thoughts in the comments
Please Login to comment...