Python for Loops
for Loops
A for loop iterates over a sequence — such as a list, tuple, set, dictionary, or string — and executes a block of code once for each item.
for city in ["Delhi", "Mumbai"]:
print(city)
Unlike the traditional for loop in languages such as C or Java, which counts with an index (for (i = 0; i < n; i++)), Python's for loop works like an iterator: it automatically moves through each item without requiring you to manage an index variable.
Syntax
for variable in iterable:
# code to run for each item
| Part | Meaning |
|---|---|
variable | A name that receives the current item on each iteration |
iterable | Any object you can loop over: a list, tuple, string, set, dictionary, range, file, and more |
| Indented block | The code that runs once per item |
Basic for Loop Example
Example: Looping Through a List
cities = ["Delhi", "Mumbai", "Chennai"]
for city in cities:
print(city)
Expected output:
Delhi
Mumbai
Chennai
How it works:
- On the first iteration, Python assigns
"Delhi"tocityand runs the block. - On the second iteration,
citybecomes"Mumbai". - On the third iteration,
citybecomes"Chennai". - There are no items left, so the loop ends.
Note: You do not need to create or update an index variable — Python handles the iteration for you. This makes
forloops shorter and less error-prone than index-basedwhileloops.
Practical Example: Calculating a Total
prices = [250, 120, 80]
total = 0
for price in prices:
total += price
print("Total:", total)
Expected output:
Total: 450
total starts at 0, and each iteration adds the current price to it. This accumulator pattern is one of the most common uses of loops.
Looping Through a String
Strings are iterable, so a for loop can visit each character in order.
Example: Iterating Over Characters
word = "Python"
for letter in word:
print(letter)
Expected output:
P
y
t
h
o
n
The break Statement
break stops the loop immediately, even if items remain.
Example: Stop When a Condition Is Met
numbers = [10, 20, 30, 40, 50]
for n in numbers:
if n == 30:
break
print(n)
Expected output:
10
20
The loop exits as soon as 30 is reached. Because break comes before print(n), 30 itself is never printed.
break After Output
The position of break matters. If you print first and then check, the matching item is displayed:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
if color == "green":
break
Expected output:
red
green
Compare it with break placed before the output:
colors = ["red", "green", "blue"]
for color in colors:
if color == "green":
break
print(color)
Expected output:
red
The continue Statement
continue skips the rest of the current iteration and moves on to the next item.
Example: Skip a Specific Value
animals = ["dog", "cat", "cow", "horse"]
for animal in animals:
if animal == "cat":
continue
print(animal)
Expected output:
dog
cow
horse
When animal is "cat", continue skips the print(); the loop then carries on with "cow".
| Statement | Effect |
|---|---|
break | Exits the entire loop |
continue | Skips to the next item |
The range() Function
To repeat a block a specific number of times, loop over range(). It generates a sequence of integers.
Basic range()
for i in range(5):
print(i)
Expected output:
0
1
2
3
4
range(5) produces five numbers, starting at 0 and stopping before 5.
range() With a Start Value
for i in range(3, 8):
print(i)
Expected output:
3
4
5
6
7
The sequence starts at 3 (included) and stops before 8 (excluded).
range() With a Step Value
The third argument sets the step — how much to add each time.
for i in range(2, 20, 4):
print(i)
Expected output:
2
6
10
14
18
A negative step counts down:
for i in range(5, 0, -1):
print(i)
Expected output:
5
4
3
2
1
| Form | Generates |
|---|---|
range(stop) | 0 up to stop - 1 |
range(start, stop) | start up to stop - 1 |
range(start, stop, step) | start, start + step, … while before stop |
range() is covered in more detail in the Python Range lesson.
Getting the Index With enumerate()
When you need both the position and the item, use enumerate():
fruits = ["mango", "apple", "kiwi"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Expected output:
0 mango
1 apple
2 kiwi
enumerate() produces (index, item) pairs, which are unpacked into the two loop variables. Pass a second argument to start counting from a different number, for example enumerate(fruits, 1).
The else Block With a for Loop
A for loop can have an else block. It runs only if the loop completes normally, without hitting break.
Example: Loop Completion
for i in range(4):
print(i)
else:
print("Loop completed successfully")
Expected output:
0
1
2
3
Loop completed successfully
else Is Skipped When break Is Used
for i in range(6):
if i == 4:
break
print(i)
else:
print("This will not be printed")
Expected output:
0
1
2
3
The loop ends with break, so the else block is skipped.
Practical Use: Searching for an Item
usernames = ["asha", "ravi", "meena"]
search = "john"
for name in usernames:
if name == search:
print("User found")
break
else:
print("User not found")
Expected output:
User not found
The else block runs only when the loop checked every name without finding a match. Think of it as "no break occurred".
Nested for Loops
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Example: Combining Two Lists
sizes = ["small", "medium"]
items = ["shirt", "jacket"]
for size in sizes:
for item in items:
print(size, item)
Expected output:
small shirt
small jacket
medium shirt
medium jacket
How it works:
- The outer loop takes
size = "small". - The inner loop runs fully:
"shirt", then"jacket". - The outer loop moves to
size = "medium", and the inner loop runs fully again.
With 2 sizes and 2 items, the inner print() runs 2 × 2 = 4 times.
Example: Multiplication Table
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end="\t")
print()
Expected output (columns separated by tabs):
1 2 3
2 4 6
3 6 9
end="\t"prints a tab instead of a newline, keeping each row on one line.- The empty
print()after the inner loop moves to the next line.
Note:
breakandcontinueaffect only the innermost loop they are in.
The pass Statement in Loops
A for loop body cannot be empty. If you need the loop structure but have no logic yet, use pass:
for i in range(3):
pass
This loop runs three times and does nothing, but it prevents a syntax error.
Looping Through Other Collections
# Tuple
for n in (1, 2, 3):
print(n, end=" ")
print()
# Dictionary (keys and values)
stock = {"pen": 10, "book": 4}
for item, quantity in stock.items():
print(item, quantity)
Expected output:
1 2 3
pen 10
book 4
Common Mistakes
| Mistake | Problem |
|---|---|
| Forgetting the colon | SyntaxError: expected ':' |
Expecting range(5) to include 5 | range stops before the stop value |
| Modifying a list while looping over it | Items may be skipped; loop over a copy (items[:]) instead |
Using range(len(items)) when only items are needed | Works, but for item in items is cleaner |
Misplacing break before or after output | Changes whether the matching item is printed |
Related Concepts
- Python while Loops — loops controlled by a condition
- Python Range — generating number sequences
- Python Iterators — how
forloops work internally - Python Lists, Tuples, Sets, and Dictionaries — common iterables