Flash cards
Review the key moves
What is the main idea behind Python Iterators?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ = ("apple", "banana", "cherry")Put the learning moves in the order that makes the concept easiest to apply.
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods iter() and next() .
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
Example
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))Even strings are iterable objects, and can return an iterator:
Example
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))Looping Through an Iterator
We can also use a for loop to iterate through an iterable object:
Example
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)Example
mystr = "banana"
for x in mystr:
print(x)The for loop actually creates an iterator object and executes the next() method for each loop.
Create an Iterator
To create an object/class as an iterator you have to implement the methods iter() and next() to your object.
As you will learn in the Python Classes/Objects chapter, all classes have a function called init() , which allows you to do some initializing when the object is being created.
The iter() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
The next() method also allows you to do operations, and must return the next item in the sequence.
Example
class MyNumbers:
def __iter__(self):
self.a =
1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter =
iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))StopIteration
The example above would continue forever if you had enough next() statements, or if it was used in a for loop.
To prevent the iteration from going on forever, we can use the StopIteration statement.
In the next() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:
Example
class MyNumbers:
def __iter__(self):
self.a =
1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass =
MyNumbers()
myiter =
iter(myclass)
for x in myiter:
print(x)