Python Iterators

Let’s look at iterators

  1. Notice

    An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))
Live state

Top-level scope

items→Object 1
iterator→Object 2
Object 1 · rangerange(0, 3)Object 2 · range_iterator<range_iterator object>
This step

An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.

Picture iterators

An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.

Image brief

Alt text
A diagram for Python Iterators. Instructions: items = range(3) iterator = iter(items) print(next(iterator, "done")) print(next(iterator, "done")). Displayed result: 0 1. The final example bindings are items --> object 1 (range); iterator --> object 2 (range_iterator). object 1: range(0, 3); object 2: <range_iterator object>
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python Iterators". Teaching focus: An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS items = range(3) iterator = iter(items) print(next(iterator, "done")) print(next(iterator, "done")) | v DISPLAYED RESULT 0 1 FINAL BINDINGS items --> object 1 (range) iterator --> object 2 (range_iterator) object 1: range(0, 3) object 2: <range_iterator object> Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python Iterators. Instructions: items = range(3) iterator = iter(items) print(next(iterator, "done")) print(next(iterator, "done")). Displayed result: 0 1. The final example bindings are items --> object 1 (range); iterator --> object 2 (range_iterator). object 1: range(0, 3); object 2: <range_iterator object>

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))
Live state

Top-level scope

items→Object 1
iterator→Object 2
Object 1 · rangerange(0, 3)Object 2 · range_iterator<range_iterator object>
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
0
1

What do you expect this program to print?

What does this example display?

items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))
What does this example display?
Choose one answer. You can try again.

Answer and explanation

0 1

Follow the printed values in order. The output is: 0 1

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.

An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.

More examples and reference

Python is built for readability and expressiveness. And when it comes to repeating actions or looping through data, iterators power some of Python’s most elegant features. If you’ve used a for loop in Python, you’ve already touched iterators — you just may not have realized it.

What Is an Iterator?

An iterator is an object that represents a stream of data — it returns one item at a time when you call next() on it. The iterator remembers where it left off and continues from there, making it highly efficient for looping over large datasets or infinite sequences.

Iterable vs Iterator

Before diving deeper, let’s differentiate between two terms:

  • Iterable: An object capable of returning its members one at a time. Example: lists, strings, tuples.
  • Iterator: An object which implements the __iter__() and __next__() methods. It produces values one at a time using next().

Creating an Iterator

Let’s see a simple example where we manually use an iterator.

numbers = [10, 20, 30]
iterator = iter(numbers)

print(next(iterator))  # Step 1
print(next(iterator))  # Step 2
print(next(iterator))  # Step 3
10
20
30

What Happens If You Go Too Far?

Once the iterator is exhausted, calling next() again raises a StopIteration exception.

numbers = [10, 20, 30]
iterator = iter(numbers)

print(next(iterator))  # Step 1
print(next(iterator))  # Step 2
print(next(iterator))  # Step 3
print(next(iterator))  # Raises StopIteration
1
Traceback (most recent call last):
  ...
StopIteration

Using Iterators in Loops

Typically, we don’t use next() manually. Instead, we let Python handle it through a for loop:

for char in "Hi":
    print(char)
H
i

Behind the scenes, Python does:

  1. Calls iter("Hi")
  2. Calls next() until StopIteration is raised

Custom Iterator Class

You can create your own iterator by defining a class with __iter__() and __next__() methods.

class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        value = self.current
        self.current += 1
        return value

count_up_to_3 = Counter(3)
for number in count_up_to_3:
    print(number)
0
1
2

Checks and Best Practices

  • Always check whether the object is iterable using hasattr(obj, '__iter__')
  • Never call next() blindly unless you handle StopIteration using a try-except block
  • Use iterators when working with large or infinite data to avoid memory bloat

How to Verify If an Object Is an Iterator?

from collections.abc import Iterator

print(isinstance(iter([1, 2, 3]), Iterator))  # True
print(isinstance([1, 2, 3], Iterator))        # False
True
False

Summary

Python iterators offer a powerful way to work with sequences efficiently. Understanding how they work under the hood gives you greater control and performance in your programs.

What to remember

Connect what you noticed in the example with the idea below.

Remember

An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.

Watch out for this idea

Calling next() restarts the iterator from its first element.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python Generators →