A for loop in Python walks through a collection, one item at a time. Unlike many languages, it does not count — it iterates.
for fruit in ["apple", "banana", "mango"]:
print(fruit)Looping over anything with items#
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 defaultrange: when you want to count#
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 1range(start, stop, step) never includes the stop value. That is consistent with list positions starting at 0.
enumerate: item and position together#
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#
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#
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#
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 5Python also lets a loop have an else, which runs only if the loop finished without hitting break:
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#
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:
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#
- Python lists explained
- Python dictionaries explained
- Build a to-do list app
- Python while loops — for when you do not know how many times