Generators
Generators
class with __iter__() and __next__() method, keep track of internal states,
raise StopIterationwhen there was no values to be returned etc.
This is both lengthy and counter intuitive. Generator comes into rescue in such
situations.
Python generators are a simple way of creating iterators. All the overhead we
mentioned above are automatically handled by generators in Python.
Example:
def my_gen():
n=1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
Python generators using Loop:
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1,-1,-1):
yield my_str[i]
Benefits of Generators:
Memory Efficient
A normal function to return a sequence will create the entire sequence in memory
before returning the result. This is an overkill if the number of items in the
sequence is very large.
Easy to Implement