Member-only story
Iterators Explained: The Magic Behind Your For Loops 🪄
💡 Heads Up! Click here to unlock this article for free if you’re not a Medium member!

Ever wondered what really happens when you write a for
loop? Or why some objects work with loops while others don't? Let me share a story. I was pair programming with a colleague when they asked, “Why can we loop through a list but not an integer?” That’s when I realized: many Python developers use iterators daily without truly understanding them. Let’s change that!
Iterables vs Iterators: The Simple Truth 🎭
Think of it this way:
- An iterable is like a book 📚
- An iterator is like your bookmark 🔖
The book (iterable) contains all the content, but the bookmark (iterator) keeps track of where you are.
numbers = [1, 2, 3] # This is an iterable ✨
iterator = iter(numbers) # This creates an iterator 🔄
What’s Really Happening in a For Loop? 🔄
Here’s the mind-blowing part: every for
loop you've ever written is secretly using iterators! This:
for number in [1, 2, 3]:
print(number)
Is actually doing this behind the scenes:
# What Python does under the hood 🎩✨
iterator = iter([1, 2, 3])
while True:
try:
number = next(iterator)
print(number)
except StopIteration:
break
Cool, right? 😎
When we use a for
loop in Python, we're actually using an iterator to traverse over a sequence (like a list, tuple, or string) or any other iterable object. The behavior of the for
loop is more than just a simple syntactic structure—under the hood, Python is working with iterators and the iterator protocol.
In technical terms, an iterable is an object that implements the __iter__()
method. This method is responsible for returning an iterator—an object that keeps track of the current position and knows how to retrieve the next value.
my_list = [1, 2, 3]
In this case, my_list
is an iterable.