GENERATORS IN PYTHON

A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the “yield” keyword. But we can only do that once because their values don’t persist in memory, they get their values on the fly. Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

  • We can replace loops with generators for efficiency calculating results involving large data sets.
  • Generators are useful when we don’t want all the results and wish to hold back for some time.
  • Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
def myGenerator():
    print('First item')
    yield 10

    print('Second item')
    yield 20

    print('Last item')
    yield 30

In the above example, myGenerator() is a generator function. It uses yield instead of return keyword. So, this will return the value against the yield keyword each time it is called.

Generator Expression

Python also provides a generator expression which is a shorter way of defining simple generator functions. Generator expression is an anonymous generator. The following is a generator expression for the squareOfSequence() function.>>>

squres = (x*x for x in range(5))

print(next(squre))
0

print(next(squre))
1

print(next(squre))
4
print(next(squre))
9
print(next(squre))
16

In the above example, (x*x for x in range(5)) is a generator expression. The first part of an expression is the yield value and the second part is the for loop with the collection.

Leave a comment

Design a site like this with WordPress.com
Get started