Iterator is an object in python which implements two methods, iter and next. We can iterate over it by using for loop.
class Cubes(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self): return self
def next(self):
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start*self.start
self.start += 1
return current
iterator = Cubes(a, b)
it = Cubes(1,5) # gives an iterator object which on iteration will give cubes of values 1-4
for cube in it:
print(cube)
*output*
1
8
27
64
Generator functions are the function which have yield statement instead of return. Unlike the return statement yield gives the next object, each time we call it.
Every Generator is an iterator but not every iterator is a generator. Generator syntax is simpler that iterator.
def cubes(start, stop):
for i in range(start, stop):
yield i * I * i
generator = cubes(a, b)
Generator expressions are like list comprehensions. Instead of square bracket, it is enclosed within parenthesis.
generator = (i*i*i for i in range(a, b))
We can iterate over it in a loop.