Iterators in Python
Python Shorts — Part 2

An iterator in Python is an object which can be iterated over — i.e. it has a set number of elements, and we can loop over these.
This concept is for example used in for loops:
my_list = [0, 1, 2, 3, 4]
for el in my_list:
print(el)Under the hood, an iterator needs to implement the functions __iter__ and __next__, which we will investigate in a bit.
Many other functions, such as list() or sum(), work with iterators:
print(sum(my_list))Behind the Scenes
Now let’s go a bit deeper and understand what is going on behind the scenes — and implement our own iterator.
As stated above, iterators need to implement the functions __iter__ and __next__. __iter__ is similar to the constructor of common classes (__init__), but needs to return the iterator itself. __iter__ is then actually used for iterating over the object, returning one element per call — and raises a StopIteration() if no more elements are available.
Let us showcase this by defining an iterator which returns the first n square numbers:
class SquareIterator:
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**2
else:
raise StopIteration()As promised, we can now do all the things we can do with “default” iterators you might have used before, such as:
for x in SquareIterator(5):
print(x)
print(sum(SquareIterator(5)))This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:
- Part 1: Lambda Functions in Python
- Part 3: Generators and Generator Expressions in Python
- Part 4: Advanced Iteration in Python with enumerate() and zip()
- Part 5: Managing Resources in Python with Context Managers (with statement)
- Part 6: Generating Temporary Files and Directories in Python
- Part 7: Logging in Python
- Part 8: Partial Functions in Python
- Part 9: f-Strings in Python
