In this article, we will discuss about the yield keyword and how to write a generator functions using the yield keyword in python.
Yield keyword in python is used in generator functions to return a generator object. To understand more about yield, first let us take a deeper look towards the generator functions.
Generator functions
A generator function is a special type of function which returns a generator object when called.
In normal functions, after processing the entire data the final value will be returned where as the generator functions can be paused and resumed, allowing for the generation of a sequence of values over time.
Following is the example generator function that yields successive numbers:
def count_up_to(n):
i = 0
while i <= n:
yield i
i += 1
In this example, the count_up_to
function uses the yield
keyword to generate successive values of i
until it reaches the value of n
.
gen = count_up_to(5)
In the above example, the gen
is a generator object that we can use to generate successive values of i
by calling the next
method. Once the value of i
reaches n
, the generator function exits and raises a StopIteration
exception.
print(next(gen)) # Output: 0
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
print(next(gen)) # Output: 3
print(next(gen)) # Output: 4
print(next(gen)) # Output: 5
Using yield with collections
we can also use the yield
to iterate over a collection.
Following is an example
def to_uppercase(strings):
for s in strings:
yield s.upper()
In the above example, the to_uppercase
function takes a collection of strings and uses yield
to generate uppercase versions of each string.
strings = ['foo', 'bar', 'baz']
for s in to_uppercase(strings):
print(s)
Output
FOO
BAR
BAZ