01 / 21

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.

Python

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.

Lists
\( [1, 2, 3] \) can be looped item by item
Strings
\( \text{"hello"} \) yields 'h', 'e', 'l', 'l', 'o'
Dicts
\( \{"a": 1\} \) loops over keys by default

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.

'a' 'b' 'c' 'd' 'e'
\( \text{next}() \)
already visited yet to visit Stop Iteration

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.

Memory Efficient
Iterators produce one value at a time: no need to store everything in memory
Lazy Evaluation
Values are computed only when requested, saving time and resources
Universal Protocol
All Python loops, comprehensions, and unpacking rely on this same protocol

The Iterator Protocol

Iterable
has \( \text{__iter__}() \)
\( \text{iter}() \)
Iterator
has \( \text{__next__}() \)
\( \text{next}() \)
returns value value1, value2, ... StopIteration exhausted

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:

Step 1
Call \( \text{iter([1, 2, 3])} \) to create an iterator object
Step 2
Call \( \text{next(iterator)} \) repeatedly, assigning each result to \( x \)
Step 3
Catch StopIteration and exit the loop cleanly
# What Python does behind the scenes: _iter = iter([1, 2, 3]) while True: try: x = next(_iter) print(x) except StopIteration: break

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}() \)

1
Start with an iterable. This could be a list, string, tuple, dictionary, or any object with \( \text{__iter__}() \).
2
Call \( \text{iter}() \) on it. This returns a fresh iterator object that points to the first element.
3
Call \( \text{next}() \) to fetch values. Each call advances the cursor and returns the current element.
4
Handle StopIteration. When the iterator is exhausted, \( \text{next}() \) raises StopIteration. Use try/except or a \( \text{for} \) loop to handle this.
5
Create a new iterator to restart. Iterators are one-use. Call \( \text{iter}() \) again on the original iterable to loop from the beginning.

Example 1: Basic \( \text{iter}() \) and \( \text{next}() \)

colors = ["red", "green", "blue"] # Step 1: Create an iterator it = iter(colors) # Step 2: Pull values one at a time print(next(it)) # "red" print(next(it)) # "green" print(next(it)) # "blue" # Step 3: No more values print(next(it)) # StopIteration!

Example 2: Iterating Over a String

word = "Hi!" it = iter(word) print(next(it)) # 'H' print(next(it)) # 'i' print(next(it)) # '!'
'H' 'i' '!' Stop
\( \text{next}() \) #1
\( \text{next}() \) #2
\( \text{next}() \) #3

Example 3: Iterator Exhaustion

nums = [10, 20] it = iter(nums) print(list(it)) # [10, 20] print(list(it)) # [] <-- empty! Iterator is exhausted # Fix: create a NEW iterator it2 = iter(nums) print(list(it2)) # [10, 20] <-- works again!

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.

it = iter([42]) print(next(it, "done")) # 42 print(next(it, "done")) # "done" (no error!) print(next(it, "done")) # "done" (still safe)

Checking: Iterable or Iterator?

from collections.abc import Iterable, Iterator my_list = [1, 2, 3] my_iter = iter(my_list) print(isinstance(my_list, Iterable)) # True print(isinstance(my_list, Iterator)) # False print(isinstance(my_iter, Iterable)) # True print(isinstance(my_iter, Iterator)) # True

The Full Picture

\( \text{for x in iterable:} \)
\( \text{_it = iter(iterable)} \)
\( \text{x = next(_it)} \)
repeat
\( \text{StopIteration} \rightarrow \text{break} \)
Step 1 Step 2 Step 3

Common Mistakes

✕ Reusing an Exhausted Iterator
Calling \( \text{next}() \) or \( \text{list}() \) on an already-consumed iterator returns nothing. Always create a new iterator with \( \text{iter}() \).
✕ Calling \( \text{next}() \) on an Iterable
\( \text{next}([1,2,3]) \) raises TypeError. You must call \( \text{iter}() \) first to get an iterator, then call \( \text{next}() \) on that.
✕ Forgetting StopIteration
Calling \( \text{next}() \) too many times without a try/except or default value will crash your program with an unhandled StopIteration.

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?

it = iter("Python") next(it) next(it) print(next(it))

Question 4 of 5

Which statement about iterables and iterators is true?

Question 5 of 5

What is the output of this code?

it = iter([5, 10]) print(next(it, 0)) print(next(it, 0)) print(next(it, 0))