Generators in Python
Generators are functions that return a sequence of values . A generator function is written like an ordinary function but it uses 'yield' statement . This statement is useful to return a value .
Example , one can write a generator function to return numbers from x to y .
# here , the generator function name is 'mygen'
def mygen(x,y):
while x <= y :
yield x
x = x + 1 # increment value of x by 1
One can call this function by passing the values 5 and 10 as follows :
gen_obj = mygen(5,10)
Here , the mygen() function returns a generator object that contains sequence of numbers as returned by 'yield' statement . So 'gen_obj' refers to the generator object with a sequence of numbers from 5 to 10 . One can display the numbers from the "gen_obj" .One can display the numbers from "gen_obj" using display the numbers from "gen_obj" using a for loop as :
for i in g:
print(i,end=' ')
In the following program , one can create a generator function that generates numbers from x to y and display those numbers .
Python program to create a generator that returns a sequence of numbers from x to y
# generator returns sequence from x to y
def mygen(x,y):
while x <= y:
yield x
x = x + 1
# fill generator object with 5 and 10
gen_obj = mygen(5,10)
# display all numbers in the generator
for i in gen_obj:
print(i,end = ' ')
Output
5 6 7 8 9 10
Once the generator object is created , we can store the elements of the generator into a list and use the list as we want . For example , to store the numbers of generator 'gen_obj' into a list 'lst' one can use the list() function as :
lst = list(gen_obj)
Now , the list 'lst' contains the elements:
[5 6 7 8 9 10]
If we want to retrieve element by element from a generator object , one can use the next() function as :
print(next(gen_obj))
which would display the first element in "gen_obj". And , when we call the above function the very next time , it will display the second element in "gen_obj" and by repeatedly calling the next() function , we would be able to display all the elements of "gen_obj" .
In the following program , a simple generator is created that returns 'A','B','C'
def mygen():
yield 'A'
yield 'B'
yield 'C'
Here , mygen() is returning 'A','B','C' using yield statements . Here , yield statement returns the elements from a generator function into a generator object . And , when we call the mygen() function , it is expressed as follows :
gen_obj = mygen()
Here , the characters 'A','B','C' are present within the generator object "gen_obj" and they can be referred and called into use using the next(gen_obj) function to refer to the elements .
No comments:
Post a Comment