Generator function in Python is a function that is commonly used to return a sequence of values. Generator function behaves like a normal function but rather it uses a yield statement to return a value instead of return statement. If the body of a function contains yield statement, the function automatically becomes a generator function.
Syntax
def gnr_fun():
yield 1
..... .
yield 10
A generator function in Python can have multiple yield statements.
Program : To illustrate the working of Generator function.
# generator function that yields counting from 0 to n
def count(n):
for i in range(0, n+1):
yield i
# now calling generator function, gen_obj is termed as generator object
gen_obj = count(10)
# returns generator object, needed to be typecasted
print(gen_obj)
print(list(gen_obj))
O/P
<generator object count at 0x7f6f81e4a580>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If we want to generate the values one by one, rather than printing it at once, we can use next() function in python. For instance, above code can be written as :
# generator function that yields counting from 0 to n
def count(n):
for i in range(0, n+1):
yield i
# now calling generator function, gen_obj is termed as generator object
gen_obj = count(10)
# returns the element
print(next(gen_obj)) # gives 0
print(next(gen_obj)) # gives 1
print(next(gen_obj)) # gives 2
print(next(gen_obj)) # gives 3
print(next(gen_obj)) # gives 4
print(next(gen_obj)) # gives 5
Note, if you are already at the end of the list, and try to use next(), then it will result in an exception StopIteration, signaling the end of the iteration.
That’s all about Generator Functions in Python.
