http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
Iterators and Generators
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
Python Programming Essentials
© SkillBrew http://skillbrew.com
Iterators
© SkillBrew http://skillbrew.com
Iterable objects
ď‚§ Iterable objects are those that can be used
with a for loop
© SkillBrew http://skillbrew.com
Examples of iterable objects
>>> for i in [1, 2, 3, 4]:
... print i,
...
1 2 3 4
>>> for c in "python":
... print c,
...
p y t h o n
>>> for k in {"x": 1, "y": 2}:
... print k,
...
y x
© SkillBrew http://skillbrew.com
Many functions consume iterables
>>> ",".join(["a", "b", "c"])
'a,b,c'
>>> ",".join({"x": 1, "y": 2})
'y,x'
>>> list("python")
['p', 'y', 't', 'h', 'o', 'n']
>>> list({"x": 1, "y": 2}) ['y', 'x']
© SkillBrew http://skillbrew.com
iter function
ď‚§ The built-in function iter takes an
iterable object and returns an iterator
© SkillBrew http://skillbrew.com
iter function example
>>> x = iter([1, 2])
>>> x <listiterator object at 0x1004ca850>
>>> x.next()
1
>>> x.next()
2
>>> x.next()
Traceback (most recent call last): File
"<stdin>", line 1, in <module>
StopIteration
© SkillBrew http://skillbrew.com
Iteration protocol
ď‚§ 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.
© SkillBrew http://skillbrew.com
Implementing iterator as a class
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()
© SkillBrew http://skillbrew.com
Implementing iterator as a class (2)
ď‚§ 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
ď‚§ Iterator should have a next method and
should raise StopIteration when there are
no more elements
© SkillBrew http://skillbrew.com
Implementing iterator as a class (3)
>>> y = yrange(2)
>>> y.next()
0
>>> y.next()
1
>>> y.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in next StopIteration
© SkillBrew http://skillbrew.com
Iterator performance
ď‚§ Iterators implemented in code are much
more efficient than iterators backed by
memory based datastructures
ď‚§ Iterators implemented in code do not use
any memory
ď‚§ Eg. List from range() vs. xrange()
© SkillBrew http://skillbrew.com
Generators
© SkillBrew http://skillbrew.com
Generators
ď‚§ Generators simplifies creation of iterators
ď‚§ A generator is a function that produces a
sequence of results instead of a single
value
ď‚§ So a generator is also an iterator
 With generator, you don’t have to worry
about the iterator protocol
© SkillBrew http://skillbrew.com
Generator example
def yrange(n):
i = 0
while i < n:
yield i
i += 1
Each time the yield statement is executed the
function generates a new value.
© SkillBrew http://skillbrew.com
Generator example (2)
>>> y = yrange(2)
>>> y <generator object yrange at 0x401f30>
>>> y.next()
0
>>> y.next()
1
>>> y.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module> StopIteration
© SkillBrew http://skillbrew.com
Generator example – Squares
def squares(n):
for i in xrange(n):
yield i * i
© SkillBrew http://skillbrew.com
Generator Expressions
>>> a = [x*x for x in range(10)]
>>> a
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> b = (x*x for x in xrange(10))
>>> b
>>> <generator object <genexpr> at
0x1c46410>
>>> list(b)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Python Programming Essentials - M35 - Iterators & Generators

Python Programming Essentials - M35 - Iterators & Generators