You are on page 1of 8

Iterators & Generators

Python Intermediate #5
Iterators
• Used to loop through the items of a container.
• You will have used them before!
for element in [1, 2, 3]
• Python uses the iter() method to return an
iterator object of the class.
• The iterator object then uses the next() method
to get the next item.
• The for loop stops when the StopIteration
Exception is raised.
Iterator Example
s = 'abc'
it = iter(s)
it.next()
'a'
it.next()
'b'
it.next()
'c'
it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
it.next()
StopIteration
Lets try it out
• reverse.py
Generators
• Another way of creating iterators.
• Uses a function rather than a separate class
• Generates the background code for the next()
and iter() methods
• Uses a special statement called yield which
saves the state of the generator and set a
resume point for when next() is called again.
Generator Expressions
• Generator Expressions are a unique feature
that python uses.
• Allows for iteration to be handled in a single
line expression.
• Uncommonly used by a lot of programmers.
Recreate reverse
• We will use a generator this time
• Then we will try a generator expression
Next
• Modulating our code

• Extra Code will be in the code.txt file in the


slides folder. As well as a challenge.

• Feel Free to leave questions in the comments


I’ll try to answer all of them.

You might also like