Codementor Events

Generators in Python

Published Apr 18, 2019

Generator is a python function that returns an iterable object from a generated sequence one at a time. Instead of the standard return statement a yield statement is used. When the interpreter is evaluating the function definition, the presence of the yield statement is what categorizes the function as a generator. On each call to the generator the yield statement returns only one value from the iterable or range of values. The return value points to the current element. The next element can be accessed by calling generate.next().

Let's assume for example that you are a professor at a university doing cutting edge research and NSF has agreed to fund your project with promised amount of $24000/year but will only transfer $6000 quarterly to your account after you've delivered on the research on a semester basis.

x = [1,2,3,4]
y = [10,20,30,40]

def gentr_fn(x,y):
    for i in x:
        yield i
    while 1:
        for j in y:
            yield j

a = gentr_fn(x,y)
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()

>>gentr_fn(x,y)
1 2 3 4 10 20 30 40 10 20

Another simple example to keep in mind to understand the working of a generator is an ATM machine or a coin operated milk booth.

Discover and read more posts from Arch B
get started
post commentsBe the first to share your opinion
Show more replies