Python For Loops
Learn how Python for loops work: syntax, range(), enumerate(), break, continue, else, nested loops, and iterating over lists, strings, and dicts.
A for loop in Python iterates over every item in a sequence — a list, tuple, string, dictionary, set, or any other iterable — and executes a block of code once per item. Unlike languages where for typically counts numbers, Python's for is a for-each loop that walks through items directly.
This chapter covers:
- Basic syntax and how the loop variable works
- The
range()function for counted loops break,continue, and theelseclauseenumerate()andzip()for richer iteration- Iterating over strings, dictionaries, and nested structures
- Nested
forloops - The
passstatement as a placeholder
Basic syntax
for variable in iterable:
# block executed once per itemvariable is assigned each successive item from iterable. The indented block runs once for every item.
Iterating over a list
Output:
apple
banana
cherryThe loop assigns "apple" to fruit, runs print(fruit), then moves on to "banana", and so on until all items are exhausted.
Iterating over a string
A string is itself an iterable — each character is an item:
for ch in "Python":
print(ch)Output:
P
y
t
h
o
nThe range() function
range() generates a sequence of integers on demand. It is the most common way to run a loop a specific number of times.
range(stop)
range(start, stop)
range(start, stop, step)| Parameter | Default | Meaning |
|---|---|---|
start | 0 | First value (inclusive) |
stop | required | Upper bound (exclusive) |
step | 1 | Increment between values |
Counting from 1 to 5
Output:
1
2
3
4
5range(1, 6) produces 1, 2, 3, 4, 5 — the stop value 6 is not included.
Counting in steps
for i in range(0, 10, 2):
print(i)Output:
0
2
4
6
8Counting backwards
A negative step iterates in reverse:
for i in range(10, 0, -2):
print(i)Output:
10
8
6
4
2The break statement
break exits the loop immediately, before all items have been visited.
for i in range(1, 6):
if i == 3:
break
print(i)Output:
1
2Once i equals 3, break fires and the loop stops — 3, 4, and 5 are never printed.
When to use break: searching a list and stopping as soon as you find a match; exiting early from a long computation.
The continue statement
continue skips the rest of the current iteration and moves straight to the next item.
for i in range(1, 6):
if i == 3:
continue
print(i)Output:
1
2
4
5When i equals 3, continue skips print(i) and jumps to i = 4.
The else clause
Python's for loop supports an optional else block that runs only if the loop completed normally (i.e., was not terminated by break).
for i in range(1, 4):
print(i)
else:
print("Loop finished")Output:
1
2
3
Loop finishedIf the loop exits via break, the else block is skipped:
for i in range(1, 6):
if i == 3:
break
print(i)
else:
print("Loop finished without break")Output:
1
2The else clause is useful for signalling whether a search succeeded — if you break on a match, the else block only runs when no match was found.
enumerate() — loop with index and value
enumerate() pairs each item with its position index, so you get both in one loop without a separate counter variable.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)Output:
0 red
1 green
2 blueTo start counting from a different number, pass start:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)Output:
1 apple
2 banana
3 cherryzip() — loop over two sequences at once
zip() pairs items from two (or more) iterables side by side:
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(name, score)Output:
Alice 95
Bob 87
Charlie 92zip() stops when the shortest iterable is exhausted.
Iterating over dictionaries
Iterating over a dictionary by default yields its keys:
person = {"name": "Alice", "age": 30, "city": "Paris"}
for key in person:
print(key, ":", person[key])Output:
name : Alice
age : 30
city : ParisUse .items() to get key-value pairs together:
for key, value in person.items():
print(key, ":", value)Output:
name : Alice
age : 30
city : ParisSee also the Loop Dictionaries chapter for more patterns.
Nested for loops
A for loop can be placed inside another for loop. The inner loop runs fully for every single iteration of the outer loop.
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherryGotcha: break inside a nested loop only exits the inner loop, not both. To exit both loops at once you need a flag variable or to refactor into a function and use return.
The pass statement
pass is a no-op placeholder. Use it when a for loop is syntactically required but you have nothing to put in the body yet:
for i in range(3):
pass # TODO: implement laterWithout pass, Python would raise an IndentationError because an empty block is invalid syntax.
For loops vs list comprehensions
A common pattern is building a new list inside a for loop:
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares)Output: [1, 4, 9, 16, 25]
Python offers a more concise alternative called a list comprehension:
squares = [x ** 2 for x in range(1, 6)]
print(squares)Output: [1, 4, 9, 16, 25]
List comprehensions are idiomatic for simple transformations; use a regular for loop when the body is complex or has side effects.
Choosing between for and while
| Situation | Prefer |
|---|---|
| You know the number of iterations or have an iterable | for |
| You loop until a condition changes | while |
| You need index and value | for + enumerate() |
| You loop over two lists together | for + zip() |