Day10

Pramod Ray
1 min readSep 23, 2019

Iterator : Iterator in python is simply an object that can be iterated . An object which will return data, one element at a time.

Python iterator object must implemented two special method, iter() and next(), collectively called the iterator protocol.

The iter() function(which is turn calls the iter() method) returns an iterator from them.

Syntax iter()
list = [1,2,3,4,5]
listIter = iter(list)
print(next(listIter))
print(next(listIter))
print(next(listIter))
print(next(listIter))
print(next(listIter))

Generator : A python generator is a kind of an iterable, like a python list or a python tuple. It generates for us a sequence of values that we can iterate on.

If function contains at least one yield statement (it may contain other yield or return statement s), It becomes a generator function. Both yield and return will return some value from a function.

Syntax:
def counter():
i=1
while(i<10):
yield i
i+=1
Example :
def my_gen(x):
while(x>0):
if x%2==0:
yield 'even'
else:
yield 'odd'
x-=1
for i in my_gen(7):
print(i)

--

--