Iterables &
Iterators
Understand how Python loops really work under the hood using \( \text{iter}() \) and \( \text{next}() \), the building blocks of every \( \text{for} \) loop.
What Is an Iterable?
An iterable is any Python object you can loop over. If you can write \( \text{for x in thing} \), then \( \text{thing} \) is an iterable. Lists, strings, tuples, dictionaries, sets, and files are all iterables.
What Is an Iterator?
An iterator is a stateful object that remembers where it is in a sequence and knows how to get the next value. Think of it like a bookmark moving through a book: it only moves forward, one page at a time.
Why Iterators Matter
Every \( \text{for} \) loop in Python is secretly using iterators behind the scenes. Understanding this mechanism lets you write memory-efficient code, create custom sequences, and grasp how generators and file objects work.
The Iterator Protocol
How \( \text{for} \) Loops Really Work
When Python executes \( \text{for x in [1, 2, 3]} \), it does not magically know the elements. It follows the iterator protocol:
Iterable vs Iterator
| Iterable | Iterator | |
|---|---|---|
| What it is | A container of data | A cursor walking through data |
| Key method | \( \text{__iter__}() \) | \( \text{__next__}() \) |
| Reusable? | Yes: can create fresh iterators | No: exhausted after one pass |
| Examples | list, str, dict, set | list_iterator, file object |
| Analogy | A book | A bookmark in a book |
How to Use \( \text{iter}() \) and \( \text{next}() \)
Example 1: Basic \( \text{iter}() \) and \( \text{next}() \)
Example 2: Iterating Over a String
Example 3: Iterator Exhaustion
Avoiding Errors with \( \text{next}(\text{it}, \text{default}) \)
You can pass a second argument to \( \text{next}() \) as a default value. Instead of raising StopIteration, Python returns the default when the iterator is exhausted.
Checking: Iterable or Iterator?
The Full Picture
Common Mistakes
Summary Reference
| Concept | Syntax | Result |
|---|---|---|
| Create iterator | \( \text{iter(obj)} \) | Returns an iterator from obj |
| Get next value | \( \text{next(it)} \) | Returns next item or raises StopIteration |
| Safe next | \( \text{next(it, default)} \) | Returns next item or default |
| Check iterable | \( \text{isinstance(obj, Iterable)} \) | True/False |
| Check iterator | \( \text{isinstance(obj, Iterator)} \) | True/False |
| Restart iteration | \( \text{iter(obj)} \) again | Fresh iterator from start |
Question 1 of 5
Which built-in function converts an iterable into an iterator?
Question 2 of 5
What happens when you call \( \text{next}() \) on an exhausted iterator (with no default)?
Question 3 of 5
Given the code below, what does \( \text{print(next(it))} \) output?
Question 4 of 5
Which statement about iterables and iterators is true?
Question 5 of 5
What is the output of this code?