Iterable Objects vs Iterators in Python
What Are Iterable Objects?
An iterable is any Python object that implements the __iter__ method. Think of it like a book—the book has pages you can flip through one by one, making it iterable. A rock, on the other hand, cannot be iterated over since it has no sequential access capability.
Common built-in iterables include lists, strings, tuples, and dictionaries.
What Are Iterators?
An iterator is an iterable that also implements the __next__ method. To visualize the difference, consider an ammunition magazine versus a magazine loaded into a gun:
- The magazine alone is like a list—you can see all the rounds and access any position directly
- The magazine loaded into a gun is like an iterator—you can only access rounds sequentially by pulling the trigger (calling
next())
The __iter__ method handles the "loading" action, while __next__ handles the "firing" action that retrieves subsequent elements.
Key Characteristics of Iterators
- Iterators maintain internal state to remember where traversal currently stands
- Elements are accessed sequentially starting from the first item until exhausted
- Iterators can only move forward—never backward
- Two fundamental methods exist:
iter()to initialize andnext()to advance
Working with Iterators
Creating an iterator from a sequence:
>>> data = [5, 10, 15, 20]
>>> iterator = iter(data)
>>> print(next(iterator))
5
>>> print(next(iterator))
10
Iterating using a for loop:
data = [5, 10, 15, 20]
iterator = iter(data)
for item in iterator:
print(item, end=" ")
Manual iteration with next() and exception handling:
import sys
data = [5, 10, 15, 20]
iterator = iter(data)
while True:
try:
print(next(iterator))
except StopIteration:
sys.exit()
Practical Extraction from Iterables
Extracting all elements from an iterable follows patterns such as list comprehensions, generator expressions, or consuming the iterator entirely with list():
data = [1, 2, 3, 4]
result = [x * 2 for x in data]