For Loops
Learn how to repeat actions over a sequence using for loops in Python.
For Loops
A for loop lets you repeat a block of code for every item in a sequence. Instead of writing the same thing over and over, you write it once and tell Python to run it for each item.
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)Output:
apple
banana
mangoPython takes the list, picks each item one by one, puts it in fruit, runs the block, then moves to the next item. When there are no items left, the loop ends.
How it works
The loop always asks — is there a next item? If yes, run the block. If no, stop.
Looping over different sequences
A for loop works on anything Python can iterate over — not just lists.
String — loops over each character:
name = "Ali"
for letter in name:
print(letter)Output:
A
l
iTuple:
colors = ("red", "green", "blue")
for color in colors:
print(color)Dictionary — loops over keys by default:
person = {"name": "Ali", "age": 22, "city": "Lahore"}
for key in person:
print(key)Output:
name
age
cityTo get both key and value, use .items():
for key, value in person.items():
print(f"{key}: {value}")Output:
name: Ali
age: 22
city: Lahorerange() — looping over numbers
range() generates a sequence of numbers. You do not need a list — just tell it where to start, where to stop, and how to step.
Basic — count from 0 to 4:
for i in range(5):
print(i)Output:
0
1
2
3
4range(5) gives you 0, 1, 2, 3, 4 — it stops before 5, never including it.
Start and stop:
for i in range(1, 6):
print(i)Output:
1
2
3
4
5Start, stop, and step:
for i in range(0, 20, 5):
print(i)Output:
0
5
10
15Counting backwards:
for i in range(5, 0, -1):
print(i)Output:
5
4
3
2
1range(stop) — starts at 0, stops before stop
range(start, stop) — starts at start, stops before stop
range(start, stop, step) — same but jumps by step each time
enumerate() — loop with an index
Sometimes you need both the item and its position. enumerate() gives you both:
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")Output:
0: apple
1: banana
2: mangoYou can start the index from any number:
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")Output:
1. apple
2. banana
3. mangoWithout enumerate(), people often do this — which works but is not Pythonic:
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")Use enumerate() instead. It is cleaner and easier to read.
zip() — loop over two sequences together
zip() lets you loop over two sequences at the same time, pairing items by position:
names = ["Ali", "Sara", "Omar"]
scores = [88, 95, 72]
for name, score in zip(names, scores):
print(f"{name} scored {score}")Output:
Ali scored 88
Sara scored 95
Omar scored 72If one sequence is shorter, zip() stops at the shorter one:
names = ["Ali", "Sara", "Omar"]
scores = [88, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")Output:
Ali: 88
Sara: 95Omar has no matching score so Python stops there.
Nested for loops
A loop inside a loop. The inner loop runs completely for every single iteration of the outer loop.
rows = 3
cols = 3
for row in range(1, rows + 1):
for col in range(1, cols + 1):
print(f"({row},{col})", end=" ")
print()Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)A classic use — multiplication table:
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:3}", end="")
print()Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25Be careful with deep nesting. Two levels is usually fine. Three or more levels makes code very hard to read — consider breaking it into functions instead.
A real example
Calculate the total and average score for a student:
name = "Ali"
scores = [88, 92, 79, 95, 84]
total = 0
for score in scores:
total += score
average = total / len(scores)
print(f"Student: {name}")
print(f"Total: {total}")
print(f"Average: {average:.1f}")Output:
Student: Ali
Total: 438
Average: 87.6Summary
| Concept | Example |
|---|---|
| Loop over a list | for item in list: |
| Loop N times | for i in range(N): |
| Loop with index | for i, item in enumerate(list): |
| Loop two lists together | for a, b in zip(list1, list2): |
| Loop dict key + value | for k, v in dict.items(): |