Iterable vs Iterator
2 min read ·
An iterable is any object that can return an iterator.
It represents a collection of elements that can be looped over.
An iterable does not necessarily track iteration state itself.
Examples of iterables include
Lists
Tuples
Strings
Sets
Dictionaries
Here
numbers is iterable.Definition of Iterator
An iterator is an object that
Returns itself from
__iter__()
Returns the next value from __next__()It keeps track of the current position during iteration.
Here
it is an iterator.Key Differences Between Iterable and Iterator
| Aspect | Iterable | Iterator |
|---|---|---|
| Purpose | Represents a collection | Traverses the collection |
| Method support | Has __iter__() | Has __iter__() and __next__() |
| State tracking | Does not track state | Tracks iteration state |
| Reusability | Can create multiple iterators | Gets exhausted after use |
An iterable can create many iterators, but an iterator can be used only once.
Iterator Protocol
The iterator protocol defines how iteration works in Python.
Any object that follows this protocol can be used in a loop.
The protocol consists of two special methods.
iter() Method
The
__iter__() method returns the iterator object itself.This method is called when iteration begins.
For iterators,
__iter__() always returns self.next() Method
The
__next__() method returns the next value from the iterator.When no values remain, it raises
StopIteration.After the last value, calling
next() again raises an exception.How Python Follows the Protocol
When a
for loop starts, Python performs the following steps internally.Python calls
iter() on the iterable.
This returns an iterator.
Python repeatedly calls __next__() on the iterator.
Each returned value is assigned to the loop variable.
When StopIteration is raised, the loop ends gracefully.Although this looks simple, Python is fully relying on the iterator protocol behind the scenes.