Home Tutorials Python Tutorial Iterators
Iterators

Iterators


Definition: An iterator is an object in Python that contains a countable number of values and can be iterated upon, meaning you can traverse or step through all the values one by one. Technically, an iterator implements the iterator protocol, which consists of the methods __iter__() and __next__().

Why: Iterators work quietly behind the scenes of every for loop you write in Python. Understanding them helps you see how Python handles large sequences of data efficiently, retrieving elements one at a time only when requested, which saves system memory.

Iterable vs. Iterator

  • Iterable: Anything you can loop over (like a List, Tuple, Set, Dictionary, or String). An iterable has data, but it is not the iterator itself; it is simply capable of producing one.
  • Iterator: The actual object that manages the state and remembers its current position during a loop, fetching the next item when prompted.

Example

mytuple = ("a", "b", "c")

# 1. Get an iterator from the iterable tuple
myit = iter(mytuple)

# 2. Move through the sequence manually
print(next(myit))  # Output: a
print(next(myit))  # Output: b
print(next(myit))  # Output: c

Explanation

  • The iter() Function: This built-in function converts an iterable object (like our tuple) into a standard iterator object (myit).
  • The next() Function: Each time you pass the iterator into next(), it pulls the very next item out of the sequence.
  • The StopIteration Error: If you were to call print(next(myit)) a fourth time in this example, the program would raise a StopIteration error because the sequence has run out of elements. A for loop handles this error automatically behind the scenes to exit cleanly.

Key Notes

  • Lists, tuples, dictionaries, and sets are all **iterable objects**. They are iterable containers which you can get an iterator from.
  • Custom Iterators: You can turn any custom class into an iterator by defining __iter__() (which returns the object itself) and __next__() (which defines how to fetch the next value and when to raise StopIteration).
  • Iterators are **one-way streets**. Once you traverse through an iterator to the end, it is exhausted, and you cannot reset it or go backward; you must create a new iterator object to loop again.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Iterators to test your knowledge.

Exercise »