Python Loops Explained: for, while, and Beyond

Table of contents
Loops are one of the first concepts beginners learn in Python. They make it easy to repeat tasks — whether printing numbers, processing files, or iterating over datasets. But under the hood, there's more going on than just for
and while
. This post takes you from the basics of loops to their inner workings in Python.
🔁 What Are Loops?
A loop is a way to execute a block of code multiple times.
Python has two main loop types:
for
loop – for iterating over a sequencewhile
loop – for looping while a condition is true
# for loop example
for i in range(5):
print(i)
# while loop example
i = 0
while i < 5:
print(i)
i += 1
🧠 When to Use Which?
Use Case | Use This Loop |
Known number of iterations | for loop |
Iterating over strings, lists, etc | for loop |
Keep running until condition met | while loop |
Infinite loop until break | while True |
🧱 Loop Control: break
and continue
break
: Exit the loop earlycontinue
: Skip the rest of the current iteration
for num in range(5):
if num == 3:
break # exit loop
print(num)
# Output: 0, 1, 2
for num in range(5):
if num == 3:
continue # skip this iteration
print(num)
# Output: 0, 1, 2, 4
🧵 Behind the Scenes: What Happens Internally
➤ for
Loop Internals
Under the hood, a for
loop is just syntactic sugar over Python's iterator protocol.
✅ What it means:
“Syntactic sugar” = a simpler, cleaner way to write code that still translates to more complex internal logic.
“Python's iterator protocol” = the rules Python follows to loop over an object using
__iter__()
and__next__()
.
So basically...
This:
for x in my_list:
print(x)
Is equivalent to:
iterator = iter(my_list)
while True:
try:
x = next(iterator)
print(x)
except StopIteration:
break
Python calls the __iter__()
method on the iterable to get an iterator, and then repeatedly calls __next__()
to get each item.
🧠 What’s really happening:
Python checks: “Is
my_list
an iterable?”It calls
iter(my_list)
to get an iteratorThen repeatedly calls
next(iterator)
to get valuesIt stops when
StopIteration
is raised
You never see this complexity — because the for
loop is just sugar on top of this process.
➤ while
Loop Internals
while
is a simpler control structure. Python repeatedly checks the condition and runs the body as long as it's True
. There's no iterator involved unless you use one explicitly.
x=1
while x < 5:
# do something
print(x)
x=x+1
#OUTPUT
1,2,3,4
📦 What Is an Iterable?
An iterable is any object that you can loop over. It must implement the __iter__()
method.
Examples:
Lists
Tuples
Strings
Sets
Dictionaries
Files
You can check if something is iterable:
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
🔍 Iterable vs Iterator
Feature | Iterable | Iterator |
Definition | An object that can return an iterator | An object used to iterate over an iterable |
Methods Required | Must implement __iter__() | Must implement both __iter__() and __next__() |
Purpose | Supplies data to be looped over | Fetches one item at a time |
Common Examples | List, Tuple, String, Set, Dict, Range | Output of iter() function on an iterable |
Reusable? | Yes, you can create a new iterator from it | No, gets exhausted after use |
How to create? | Just define a collection (e.g., my_list ) | Use iter(my_list) |
Use in loop | Directly usable in for loop | Used behind the scenes by for loop via next() |
✅ Code Example
s = "abc" # s is an Iterable
it = iter(s) # it is an Iterator
next(it) # 'a'
next(it) # 'b'
⚙️ Loops in CPython Internals
In CPython (the standard Python implementation), loops work with low-level C functions.
For example, when you loop over a list:
Python calls
list.__iter__()
→ returns alist_iterator
Each call to
next()
calls C code likelistiter_next()
inlistobject.c
These internals are written in C for performance, and you can find them in the CPython source code.
✅ Summary
for
loops use iterators internallywhile
loops rely on a condition checkStrings, lists, and files are all iterables
The real magic happens through Python's iterator protocol (
__iter__()
and__next__()
)CPython uses C under the hood to make looping efficient
Loops are simple on the surface, but they connect to some of the deepest parts of Python. Understanding them thoroughly helps you write clearer, faster, and more Pythonic code.
✍️ Have a question or want more examples? Drop a comment!
Subscribe to my newsletter
Read articles from Madhura Anand directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
