Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 8 of 13

Iterators

The iterator protocol behind every for loop: __iter__ and __next__, StopIteration, the difference between an iterable and its iterator, and writing an iterator class.

Beginner 12 min read·Lesson 152 of 306 in Python Programming

Learning objectives

  • Explain how a for loop uses iter() and next()
  • Distinguish iterables from iterators
  • Write a simple iterator class

Definition

An iterator is an object that produces a stream of values one at a time through its __next__() method and raises StopIteration when no values remain. Iterators are also iterable: their __iter__() returns themselves.

Introduction

Every for loop secretly does three things: it asks the iterable for an iterator, calls next() on it repeatedly, and stops when StopIteration is raised. Once you see that, generators, files and many library objects make sense.

Why it matters

Iterators let Python process sequences of any length — even infinite ones — one item at a time. Understanding them explains why some objects can be looped over twice and others only once.

Detailed explanation

An iterable (like a list) can create iterators; an iterator keeps track of a position and hands out the next value.

for x in items is equivalent to: it = iter(items); while True: try: x = next(it) except StopIteration: break; ...body...

Each call to iter(list) creates a new, independent iterator starting at the beginning — that's why lists can be looped over many times.

An iterator's __iter__ returns itself, so looping over an iterator continues from where it is; once exhausted it stays exhausted.

To write an iterator class, implement __iter__ (return self) and __next__ (return the next value or raise StopIteration). Generators (next lessons) are a much shorter way to get the same behaviour.

Syntax

Python
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
  • __iter__ returns the iterator itself.
  • __next__ returns a value or raises StopIteration.
  • Iterators keep state.

Code examples

What a for loop really does

Python
items = ["a", "b"]
it = iter(items)
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("StopIteration: no more items")
Output
a
b
StopIteration: no more items

Iterable versus iterator

Python
nums = [1, 2, 3]
print(list(nums), list(nums)) # a list can be iterated again
it = iter(nums)
print(list(it), list(it)) # an iterator is used up
print(iter(it) is it)
Output
[1, 2, 3] [1, 2, 3]
[1, 2, 3] []
True

More examples

A custom iterator class

Python
class Countdown:
"""Iterates from start down to 1."""
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
for n in Countdown(3):
print(n, end=" ")
print()
c = Countdown(5)
print(next(c), next(c), list(c))
Output
3 2 1 
5 4 [3, 2, 1]

Step-by-step explanation

  • Countdown stores its position in self.current.
  • __next__ raises StopIteration when it reaches 0, which ends the for loop cleanly.
  • Calling next() twice consumes 5 and 4; list(c) then collects the rest from where the iterator stopped.

Expected output

Running “A custom iterator class” prints exactly:

TextOutput
3 2 1
5 4 [3, 2, 1]

Practical applications

  • File objects are iterators over lines.
  • csv.reader, database cursors and zip/map/filter objects are iterators.

Best practices

  • Prefer generators over hand-written iterator classes.
  • Convert to a list when you need several passes.
  • Don't call __next__ directly; use next().

Common mistakes

Looping twice over an iterator

Avoid

rows = csv.reader(f)
count = sum(1 for _ in rows)
for row in rows: ... # nothing left

Prefer

rows = list(csv.reader(f))

An iterator is consumed by the first pass; store items in a list if you need them again.

Forgetting StopIteration

Avoid

def __next__(self):
self.i += 1
return self.data[self.i] # IndexError at the end

Prefer

def __next__(self):
if self.i >= len(self.data):
raise StopIteration
...

Iterators must signal the end with StopIteration, which for loops understand.

Important notes

  • map, filter, zip and enumerate return iterators in Python 3, so they too can be consumed only once.

Key takeaways

  • for loops call iter() once and next() repeatedly.
  • Iterators keep position and end with StopIteration.
  • Iterables can make fresh iterators; iterators are single-pass.

Try it yourself

  1. 1
    Write an iterator class Squares(n) yielding 1, 4, 9 ... n².
  2. 2
    Show that zip() returns an iterator by trying to loop over it twice.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Comprehensions and Advanced Iteration” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module