Generators in Python are functions that return a sequence of values. You can create a generator function like any other function, but you must add the ‘yield’ keyword or statement. The ‘yield’ is used to return the value.
def mygen(a,b):
while(a<=b):
yield a #return the value a
a+=1
Link to all Python Chapters: Learn Python
In the above piece of code, we have added a generator function with the name mygen. This function accepts two values, a and b, as parameters. We added a while loop within this function that checks if the value a is less than b for every loop. The ‘yield a’ within the while loop will return the ‘a’ value for every loop.
You can call this function by passing 7 and 10 as gen = mygen(7,10). It now represents a sequence of numbers from 7 to 10. Using a for loop, you can also print the numbers returned by the declared generator function. Let us now look at a program to understand more about the same.
#Python program to illustrate the concept of generators
#generator that returns sequence from a to b
def mygen(a,b):
while(a<=b):
yield a #return the value a
a+=1
#fill generator object with 7 and 10
gen=mygen(7,10)
#display all the numbers in generator
for i in gen:
print(i, end=" ")
Output
7 8 9 10
We can use the next() function to display every element in the sequence one after the other. If you were to add the next() function to the above program, you should add it as a print(next(gen)). Let us now look at one more program to understand the same.
def mygen():
yield 'A'
yield 'B'
yield 'C'
#call generator function
gen=mygen()
#display all characters in generator
print(next(gen)) #prints 'A'
print(next(gen)) #prints 'B'
print(next(gen)) #prints 'C'
#print(next(gen)) uncommenting this line will throw an error
#because we have reahced the end of the sequence
Output
A
B
C