Q1What does this code print?for i in range(2, 6):
print(i)
for Loops with range / enumerate / zip
Get the Python for loop into your hands — iterate any collection and combine it with range, enumerate, and zip in your browser.
So far we've learned branching with if / elif and bulk checks with all() / any().
In this article, you'll pick up the for statement for running the same work across every element in a list. With if and for in your toolkit, you can write most practical day-to-day code.
Pulling out one element at a time with for
A for statement takes a repeatable object (an iterable) like a list, tuple, string, or dict, and pulls out elements one by one from the start, binding each to the variable you name and running your block each time.
The basic shape is one line of for variable in iterable: plus a 4-space-indented block.
Pull one element from the collection → assign it to the variable → run the block → on to the next, repeating until elements run out.
# Loop over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# orange
# Strings are iterable too (one character at a time)
for ch in "ABC":
print(ch)
# Prints A / B / C in turn
Don't forget the colon and 4-space indent
The for line must end with : (a colon), and each line of the block must be indented by 4 spaces (or one tab). Mismatched indentation raises IndentationError.
Looping over a dict with for
If you pass a dict to for directly, only the keys are pulled out in turn. To get the values too, .items() is the usual choice. If you only need the values, use .values().
| Form | What you get | Typical use |
|---|---|---|
| for key in d: | keys | When the key alone is enough |
| for value in d.values(): | values | When you only need the values for aggregation |
| for key, value in d.items(): | key/value pairs | When you need both — for formatted display or filtering |
user = {"name": "alice", "age": 29, "role": "admin"}
# Keys only
for key in user:
print(key)
# name / age / role
# Values only
for value in user.values():
print(value)
# alice / 29 / admin
# Keys and values together
for key, value in user.items():
print(f"{key}: {value}")
# name: alice / age: 29 / role: admin
Repeating a fixed number of times with range()
range(n) is a built-in function that returns the integer sequence from 0 to n-1, and combined with for it's the go-to way to write fixed-count loops. There are 3 common ways to call it.
| Form | Generated values | Use |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | 0 to n-1 |
| range(2, 8) | 2, 3, 4, 5, 6, 7 | Specify start and end (end is exclusive) |
| range(1, 10, 2) | 1, 3, 5, 7, 9 | Specify start, end, and step |
# Loop 0 to 4
for i in range(5):
print(i)
# Prints 0 1 2 3 4 (5 lines)
# 2 to 7
for i in range(2, 8):
print(i)
# 1 to 9 in steps of 2
for i in range(1, 10, 2):
print(i)
# Use _ when you only need the count, not the value
for _ in range(3):
print("retry...")
Naming the loop variable _ (an underscore) is a convention to immediately signal "this variable isn't used inside". i or j would still work, but reading code where they're never used makes a reader pause and ask why — so use _ when you only care about the count.
enumerate and zip for indices and parallel lists
In real-world code, you often want the position of each element as well, or you want to iterate over multiple lists in parallel. enumerate() and zip() make these much shorter and more readable.
enumerate() — looping with an index
Wrapping a list in enumerate(list) gives you (index, element) pairs in turn. It's handy for ranking displays or showing line numbers in error messages — anywhere you want to attach "which one" to each value.
products = ["apple", "bread", "milk"]
for index, name in enumerate(products):
print(f"{index}: {name}")
# 0: apple
# 1: bread
# 2: milk
# To start at 1, pass the start as the second argument
for rank, name in enumerate(products, 1):
print(f"#{rank}: {name}")
# #1: apple / #2: bread / #3: milk
zip() — iterating multiple lists in parallel
zip(list1, list2, ...) lets you pull elements at the same index together from multiple lists. It stops when the shortest list runs out, so it's safe even with mismatched lengths.
names = ["Alice", "Bob", "Carol"]
scores = [82, 91, 65]
for name, score in zip(names, scores):
print(f"{name}: {score} pts")
# Alice: 82 pts / Bob: 91 pts / Carol: 65 pts
Controlling loops with break and continue
It's common to want to stop because you found what you needed or skip just this iteration. The first uses break to leave the loop immediately; the second uses continue to skip the rest of this iteration and move to the next element.
break ends the loop itself, so the remaining elements aren't evaluated at all. continue only skips the rest of this iteration and moves on to the next element — the loop as a whole keeps going. Both are typically called from inside an if.
# break: stop as soon as we find the target
users = ["alice", "bob", "carol", "dave"]
for name in users:
if name == "carol":
print("Found it")
break
print(f"checking: {name}")
# checking: alice / checking: bob / Found it
# continue: skip 0s when summing
scores = [80, 0, 65, 0, 91]
total = 0
for score in scores:
if score == 0:
continue
total += score
print(total) # 80 + 65 + 91 = 236
In this article, we covered the big picture of for: iterating over lists and dicts, counting with range(), extending with enumerate() / zip(), and controlling flow with break / continue.
In the next article, we'll look at the while loop — used for repeating when you don't know the count up front — and how to avoid infinite loops.
Knowledge Check
Answer each question one by one.
Q2When you expand enumerate(['a', 'b', 'c'], 1) with for, what pairs are produced?
Q3What does this code print?nums = [1, 2, 3, 4, 5]
for n in nums:
if n == 3:
continue
print(n)