Advanced   Chapter 136 · 30 min read · Module 11: Advanced Python

Iterators

Learning objectives
  • After this chapter you can explain the difference between an iterable and an iterator.
  • You can use iter() and next() to walk through a sequence by hand.
  • You can handle StopIteration and use the default value of next().
  • You can write a class with __iter__ and __next__ to make your own iterator.
  • You can explain why an iterator is exhausted after one pass.

Every time you write a for loop, Python quietly uses a small piece of machinery called the iterator protocol. A list, a string, a dictionary and a file all work in a for loop because they follow the same simple rules. Once you know these rules, the for loop stops being magic and you can build your own objects that work with it.

An iterator is an object that gives you one value at a time and remembers where it stopped. This is useful when the data is large, when it is slow to produce, or when it never ends. Instead of building a huge list in memory, an iterator makes each value only when you ask for it.

In this chapter you will learn what an iterable is, what an iterator is, and how iter() and next() connect them. You will then write your own iterator classes, and you will see the common traps such as using an iterator twice.

Iterable and iterator

These two words sound alike but mean different things. An iterable is any object that can give you an iterator. Lists, tuples, strings, dictionaries, sets, ranges and files are all iterables. An iterator is the object that actually produces the values, one at a time, and keeps track of its position.

Iterable: an object with an __iter__ method that returns an iterator. You can put it after in in a for loop.
Iterator: an object with a __next__ method that returns the next value, and raises StopIteration when there are no more values. It also has an __iter__ method that returns itself.

Every iterator is an iterable, but not every iterable is an iterator. A list is an iterable, yet it has no __next__ method, so you cannot call next() on a list directly. First you ask the list for an iterator with iter().

Example 1: iter() and next() by hand
colors = ['red', 'green', 'blue']
it = iter(colors)
print(next(it))
print(next(it))
print(next(it))
try:
    next(it)
except StopIteration:
    print('no more items')
red green blue no more items

What a for loop does

A for loop calls iter() on the object once. Then it calls next() again and again. When StopIteration is raised, the loop ends quietly. The next example rewrites a for loop with a while loop so you can see each step.

Example 2: a for loop written by hand
numbers = [10, 20, 30]

# the normal way
for n in numbers:
    print(n)

# what Python does behind the scenes
it = iter(numbers)
while True:
    try:
        n = next(it)
    except StopIteration:
        break
    print(n)
10 20 30 10 20 30

Iterators are used up

An iterator remembers its position and never goes back. When it reaches the end, it is exhausted. If you loop over it again you get nothing. A list is different: each for loop asks it for a fresh iterator, so you can loop over a list many times.

Example 3: an exhausted iterator
it = iter([1, 2, 3])
print(list(it))
print(list(it))
items = [1, 2, 3]
print(list(items))
print(list(items))
[1, 2, 3] [] [1, 2, 3] [1, 2, 3]
next(it, default) returns the default instead of raising StopIteration when the iterator is finished. This is handy for safe reading.
Example 4: next() with a default value
it = iter(['a', 'b'])
print(next(it, 'done'))
print(next(it, 'done'))
print(next(it, 'done'))
a b done

Writing your own iterator class

To make your own iterator, write a class with two methods. __iter__ returns the object itself. __next__ returns the next value or raises StopIteration when the work is finished. The object stores its position in an attribute such as self.current.

Example 5: a countdown iterator
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for n in Countdown(4):
    print(n)
print(sum(Countdown(4)))
4 3 2 1 10

Because the class follows the protocol, it works with for, list(), sum(), max(), unpacking and many other tools. This is the power of a shared protocol: your own type fits into the whole language.

Separating the iterable from the iterator

The Countdown class above is both iterable and iterator, so it can be used only once. A better design for reusable data is to make the container an iterable whose __iter__ returns a new iterator each time. That is exactly how lists work.

Example 6: a reusable iterable
class Repeat:
    def __init__(self, word, times):
        self.word = word
        self.times = times

    def __iter__(self):
        return iter([self.word] * self.times)

r = Repeat('hi', 3)
print(list(r))
print(list(r))
['hi', 'hi', 'hi'] ['hi', 'hi', 'hi']

Infinite iterators and lazy values

An iterator does not need an end. The itertools module in the standard library has tools such as count() and islice() that work lazily. Lazy means that a value is made only when it is requested, so memory use stays small even for very long sequences.

Example 7: lazy values with itertools
from itertools import count, islice

evens = (n for n in count(0, 2))
print(list(islice(evens, 5)))
[0, 2, 4, 6, 8]

Built-in helpers such as enumerate(), zip(), map() and filter() also return iterators. Remember that they are used up after one pass, so convert them to a list if you need the values twice.

Python syntax

Syntax
it = iter(iterable)
value = next(it)
value = next(it, default)
Syntax
class MyIter:
    def __iter__(self):
        return self
    def __next__(self):
        # return a value or raise StopIteration
        ...

Real-world applications

  • Reading a huge file line by line without loading it all into memory.
  • Streaming rows from a database or an API page by page.
  • Creating custom collections such as trees or linked lists that work with for loops.
  • Producing endless sequences like ids or time ticks lazily.

Common mistakes

Mistake: Looping over the same iterator twice and expecting values the second time.
Fix: Create a new iterator, or store the values in a list if you need them again.
Mistake: Calling next() on a list or a string directly, which raises TypeError.
Fix: Call iter() first: it = iter(my_list), then next(it).
Mistake: Forgetting to raise StopIteration in __next__, which creates an endless loop.
Fix: Always add a stop condition that raises StopIteration.
Mistake: Forgetting return self in __iter__ of an iterator class.
Fix: An iterator's __iter__ should return self so that for loops work.

Important tips

  • Use next(it, default) when an empty iterator is possible.
  • Use list(it) to see what an iterator holds while you debug, but remember it consumes the iterator.
  • Prefer built-in tools and generators before writing a full iterator class.

Key points summary

  • An iterable can produce an iterator with iter().
  • An iterator has __next__ and raises StopIteration at the end.
  • A for loop calls iter() once and next() repeatedly.
  • Iterators are single-use; many iterables are reusable.
  • Custom classes can join the protocol with __iter__ and __next__.

Exam and interview points

  • Define iterable and iterator and state the two special methods.
  • Explain what a for loop does internally.
  • StopIteration is how an iterator signals that it is finished.
  • Dictionaries iterate over keys by default.
  • map, filter, zip and enumerate return one-shot iterators in Python 3.

Quick revision

  • iter(x) gives an iterator; next(it) gives the next value.
  • StopIteration ends the loop.
  • Iterator: __iter__ returns self, __next__ gives values.
  • Iterators get exhausted.
  • next(it, default) avoids the exception.

Frequently asked questions

Is a list an iterator?

No. A list is an iterable. It has __iter__ but no __next__. Calling iter(list) gives you a list iterator.

Why does a for loop not show StopIteration?

The for loop catches StopIteration for you and uses it as the signal to finish.

Can I restart an iterator?

No. Create a new one from the original iterable by calling iter() again.

When should I write an iterator class instead of a generator?

Use a class when you need extra methods, complex state or a reusable object. For simple cases a generator is shorter.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters