• Iterators
• Iterationprotocol
• Infinite iterators
• Generators
• Generator expressions
• Relationship between iterator and generator
• Advantages
2.
Iterators
• An iteratoris an object which allows a programmer to traverse
through all the elements of a collection, regardless of its
specific implementation.
• An iterator is an object which implements the iterator
protocol.
• The iterator protocol consists of two methods:
• The __iter__() method which must return the iterator object
and next() method which returns the next element of sequence.
3.
Examples
We use forstatement for looping over a list.
>>> for i in [1, 2, 3, 4]:
... print i,
...
1
2
3
4
4.
Examples
If we useit with a string, it loops over its characters.
>>> for c in "python":
... print c
...
p
y
t
h
o
n
5.
Examples
If we useit with a dictionary, it loops over its keys.
>>> for k in {"x": 1, "y": 2}:
... print k
...
y
x
6.
Examples
If we useit with a file, it loops over lines of the file.
>>> for line in open("a.txt"):
... print line,
...
first line
second line
7.
Iteration protocol
• Thebuilt-in function iter takes an iterable object and returns an
iterator.
• Each time we call the next method on the iterator gives us the
next element.
• If there are no more elements, it raises a StopIteration.
8.
Examples
>>> x =iter([1, 2, 3])
>>> x
<listiterator object at 0x1004ca850>
>>> x.next()
1
>>> x.next()
2
>>> x.next()
3
>>> x.next()
Traceback (most recent call last):
File <stdin>, line 1, in <module>
StopIteration
9.
Examples
class yrange:
def __init__(self,n):
self.i = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
Iterators are implemented as classes.
Here is an iterator that works like built-
in xrange function.
10.
Examples
• The __iter__method is what makes an object iterable.
• Behind the scenes, the iter function calls __iter__ method on
the given object.
• The return value of __iter__ is an iterator.
• It should have a next method and raise StopIteration when
there are no more elements.
11.
Examples
>>> y =yrange(3)
>>> y.next()
0
>>> y.next()
1
>>> y.next()
2
>>> y.next()
Traceback (most recent call last):
File <stdin>, line 1, in <module>
File <stdin>, line 14, in next
StopIteration
12.
Infinite Iterators
• Itis not necessary that the item in an iterator object has to
exhaust.
• There can be infinite iterators (which never ends).
• We must be careful when handling such iterator.
13.
Examples
>>> a =iter(InfIter())
>>> next(a)
1
>>> next(a)
3
>>> next(a)
5
>>> next(a)
7
class InfIter:
"""Infinite iterator to return all odd numbers"""
def __iter__(self):
self.num = 1
return self
def __next__(self):
num = self.num
self.num += 2
return num