Python Loops Explained: for, while, and Beyond

Madhura AnandMadhura Anand
4 min read

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:

  1. for loop – for iterating over a sequence

  2. while 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 CaseUse This Loop
Known number of iterationsfor loop
Iterating over strings, lists, etcfor loop
Keep running until condition metwhile loop
Infinite loop until breakwhile True

🧱 Loop Control: break and continue

  • break: Exit the loop early

  • continue: 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 iterator

  • Then repeatedly calls next(iterator) to get values

  • It 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

FeatureIterableIterator
DefinitionAn object that can return an iteratorAn object used to iterate over an iterable
Methods RequiredMust implement __iter__()Must implement both __iter__() and __next__()
PurposeSupplies data to be looped overFetches one item at a time
Common ExamplesList, Tuple, String, Set, Dict, RangeOutput of iter() function on an iterable
Reusable?Yes, you can create a new iterator from itNo, gets exhausted after use
How to create?Just define a collection (e.g., my_list)Use iter(my_list)
Use in loopDirectly usable in for loopUsed 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 a list_iterator

  • Each call to next() calls C code like listiter_next() in listobject.c

These internals are written in C for performance, and you can find them in the CPython source code.


✅ Summary

  • for loops use iterators internally

  • while loops rely on a condition check

  • Strings, 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!

10
Subscribe to my newsletter

Read articles from Madhura Anand directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Madhura Anand
Madhura Anand