Skip to content
Happy Programming Guide
Start learning
Python

Python For Loops Explained

How for loops work in Python: looping over lists, using range, enumerate and zip, break and continue, and building a list from a loop.

A for loop in Python walks through a collection, one item at a time. Unlike many languages, it does not count — it iterates.

Python
for fruit in ["apple", "banana", "mango"]:
    print(fruit)

Looping over anything with items#

Python
for letter in "code":
    print(letter)              # c o d e

for score in [10, 8, 9]:
    print(score * 2)

for key in {"a": 1, "b": 2}:
    print(key)                 # a b — keys by default

range: when you want to count#

Python
for i in range(5):
    print(i)              # 0 1 2 3 4

for i in range(1, 6):
    print(i)              # 1 2 3 4 5

for i in range(0, 20, 5):
    print(i)              # 0 5 10 15

for i in range(5, 0, -1):
    print(i)              # 5 4 3 2 1

range(start, stop, step) never includes the stop value. That is consistent with list positions starting at 0.

enumerate: item and position together#

Python
tasks = ["wash up", "study", "walk"]

for index, task in enumerate(tasks, start=1):
    print(f"{index}. {task}")

Use this rather than for i in range(len(tasks)). It is shorter and harder to get wrong.

zip: two lists side by side#

Python
names = ["Ada", "Sam", "Kai"]
scores = [90, 75, 82]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

zip stops at the shorter list, which is usually what you want.

Looping over a dictionary properly#

Python
prices = {"pen": 50, "book": 300}

for item, price in prices.items():
    print(f"{item}: Rs {price}")

for item in prices.keys():
    print(item)

for price in prices.values():
    print(price)

More in Python dictionaries explained.

break, continue and else#

Python
for number in range(10):
    if number == 3:
        continue          # skip this pass
    if number == 6:
        break             # leave the loop entirely
    print(number)         # 0 1 2 4 5

Python also lets a loop have an else, which runs only if the loop finished without hitting break:

Python
for user in users:
    if user["name"] == "admin":
        print("Found the admin")
        break
else:
    print("No admin in the list")

Building a list from a loop#

Python
names = ["ada", "sam", "kai"]
tidy = []

for name in names:
    tidy.append(name.title())

print(tidy)   # ['Ada', 'Sam', 'Kai']

Python has a short form for exactly this pattern:

Python
tidy = [name.title() for name in names]
long_names = [n for n in names if len(n) > 3]

Learn the loop version first. The comprehension is easier to read once you know what it is replacing.

Questions people ask#

How do I loop a fixed number of times without using the counter?

Use an underscore as the name: for _ in range(3):. It signals to other readers that the value is deliberately unused.

Can I loop backwards?

Yes — for item in reversed(items): or range(10, 0, -1) for numbers.

What is the difference between a for loop and a while loop?

Use for when you know what you are iterating over, and while when you are waiting for a condition to change. See loops explained.

Why does my loop variable still exist afterwards?

Python keeps the loop variable after the loop ends, holding the last value it had. Harmless, but do not rely on it.

Where to go next#

Next lessonPython lists explained

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *