Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Iterators Explained: The Magic Behind Your For Loops 🪄

Dhruv Ahuja
Python in Plain English
5 min readJan 20, 2025

💡 Heads Up! Click here to unlock this article for free if you’re not a Medium member!

The for loop

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.

What is an Iterator?

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response