iter() and next() builtins
Overview
The `iter()` and `next()` builtins act as the user-facing interface for the iterator protocol in Python. The `iter()` function takes an iterable object and returns an iterator by calling the object's `__iter__()` method behind the scenes. The `next()` function takes an iterator and returns the next value by calling its `__next__()` method. Think of `iter()` as "give me a bookmark" and `next()` as "turn to the next page". This mechanism is what powers every `for` loop under the hood. - `iter(object)`: Requests an iterator from the provided iterable. Returns an iterator. Raises a `TypeError` if the object does not support the iterator protocol. - `next(iterator, default)`: Retrieves the next item from the iterator. Returns the optional `default` value if the iterator is exhausted. Raises a `StopIteration` exception if exhausted and no default is provided. names = ['Alice', 'Bob'] it = iter(names) print(next(it)) print(next(it)) If you call `next()` on an exhausted iterator without a default value, Python raises a `StopIteration` exception. # The trap: Exhausting an iterator without a default it = iter([42]) print(next(it)) # 42 print(next(it)) # Raises StopIteration Providing a default value to `next()` prevents the exception crash by returning the fallback value instead. Custom iteration flows and exception handling are covered fully in `custom-iterator`.
It allows manual traversal of iterables. This is critical when you need more control than a standard `for` loop provides, such as advancing conditionally or passing the iterator across different functions.
Where used: Parsing large CSV files line-by-line, Custom paginated API clients
Why learn this
- You can manually process streams of data without loading everything into memory
- You will understand the exact mechanism Python's `for` loop uses
Code walkthrough
colors = ['red', 'green', 'blue']
color_iterator = iter(colors)
first = next(color_iterator)
second = next(color_iterator)
print(first)
print(second)
Focus: first = next(color_iterator)
Aha moment
nums = [10, 20]
it1 = iter(nums)
it2 = iter(nums)
next(it1)
print(next(it2))
Prediction: What does this print?
Common guess: 20
Calling `iter()` creates a NEW iterator object each time. `it1` and `it2` are independent bookmarks in the same `list`, so advancing `it1` does not affect `it2`.
Common mistakes
- Calling `next()` on an iterable: You cannot call `next()` directly on a `list` or `str`; you must first obtain an iterator using `iter()`, and then call `next()` on that iterator.
- Not handling `StopIteration`: If you call `next()` until the iterator is exhausted, it raises a `StopIteration` exception. You must catch this or provide a default value via `next(iterator, default)`.
Glossary
- user-facing
- The parts of a program, framework, or language that developers or end-users directly interact with. Example: `print()` is a user-facing function.
- traversal
- The process of systematically visiting or moving through every item in a collection, like a list. Example: a `for` loop performs traversal.
Recall questions
- What is the primary purpose of the `iter()` builtin?
- How can you manually retrieve the next item from an iterator?
- What happens when `next()` is called on an exhausted iterator without a default value?
Understanding checks
What happens when you run this code?
A `TypeError` is raised.
You cannot call `next()` directly on a `list` (which is an iterable, not an iterator). You must first get an iterator by calling `iter(nums)`.
What will the following code output?
`20` followed by `99`
The first `next(it)` advances past `10`. The first `print` consumes `20`. The second `print` tries to get the next item, but the iterator is exhausted, so it returns the default value `99` instead of raising `StopIteration`.
Practice tasks
Manual List Traversal
The given code creates an iterator but extracts the first two items instead of the first and third. Modify the code to return a `tuple` of the first and third items, manually ignoring the second item using the iterator.
Challenge
Safe Advancement
Write a function `get_next_or_none(iterator)` that accepts an iterator and returns the next value. If the iterator is exhausted, it should return `None` instead of letting a `StopIteration` exception crash the program. You must use the `next()` builtin's two-argument form.
Continue learning
Previous: The Iterable Protocol
Previous: Iterator Protocol and StopIteration
Next: Custom Iterator Class