What is a generator in python???
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
Difference between generator function and object???
For generator function:
If the body of a def contains yield
, the function automatically becomes a generator function.
Example:
**def** simpleGeneratorFun():
**yield** 1
**yield** 2
**yield** 3
For generator object:
Generator functions return a generator object.
Example:
**for** value **in** simpleGeneratorFun():
**print**(value)
or
x = simpleGeneratorFun()
while True:
try:
print(x.next())
except StopIteration:
break
Why we use generator???
Easy to Implement
Example to implement a sequence of power of 2 using an iterator class.
class PowTwo:
def __init__(self, max=0):
self.n = 0
self.max = max
def __iter__(self):
return self
def __next__(self):
if self.n > self.max:
raise StopIteration
result = 2 ** self.n
self.n += 1
return result
or
def PowTwoGen(max=0):
n = 0
while n < max:
yield 2 ** n
n += 1
Memory Efficient
Generator implementation of such sequences is memory friendly and is preferred since it only produces one item at a time
.
Represent Infinite Stream
Since generators produce only one item at a time
, they can represent an infinite stream of data.