🕯️ Magic Note
Python’s for loop works with any iterable object. Lists, strings, tuples, dictionaries, sets, files, and even custom objects that implement iteration. This is the Iterator Protocol, and it is a core design principle of Python. If you can loop over it with for, it is iterable.
Python
fruits = [“apple”, “banana”, “cherry”, “date”]
for fruit in fruits:
print(f”I like {fruit}”)
# Output:
# I like apple
# I like banana
# I like cherry
# I like date
Python
word = “Python”
for letter in word:
print(f”Letter: {letter}”)
# Output:
# Letter: P
# Letter: y
# Letter: t
# Letter: h
# Letter: o
# Letter: n
Python
colors = (“red”, “green”, “blue”)
for color in colors:
print(f”Color: {color}”)
# Output:
# Color: red
# Color: green
# Color: blue
Python
person = {“name”: “Emma”, “age”: 25, “city”: “London”}
# Loop through keys (default)
for key in person:
print(key)
# name
# age
# city
# Loop through values
for value in person.values():
print(value)
# Emma
# 25
# London
# Loop through both key and value (most common)
for key, value in person.items():
print(f”{key}: {value}”)
# name: Emma
# age: 25
# city: London
🕯️ Magic Note
The pattern for key, value in dictionary.items(): is one of the most useful idioms in Python. It unpacks each key-value pair into two variables in one line. Elegant and readable.
Python
# range(stop) – from 0 to stop-1
for i in range(5):
print(i, end=” “)
# 0 1 2 3 4
# range(start, stop) – from start to stop-1
for i in range(2, 6):
print(i, end=” “)
# 2 3 4 5
# range(start, stop, step) – with step size
for i in range(0, 10, 2):
print(i, end=” “)
# 0 2 4 6 8
# Negative step (count downwards)
for i in range(5, 0, -1):
print(i, end=” “)
# 5 4 3 2 1
Python
colors = [“red”, “green”, “blue”, “yellow”]
# Using enumerate
for index, color in enumerate(colors):
print(f”{index}: {color}”)
# Output:
# 0: red
# 1: green
# 2: blue
# 3: yellow
# enumerate with custom start value
for index, color in enumerate(colors, start=1):
print(f”{index}: {color}”)
# 1: red
# 2: green
# 3: blue
# 4: yellow
🕯️ Magic Note
enumerate() is more Pythonic than using range(len(list)). It is cleaner, faster, and directly expresses your intent: “I need both the index and the value.”
Python
names = [“John”, “Sara”, “Mike”]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f”{name}: {score}”)
# Output:
# John: 95
# Sara: 87
# Mike: 92
# zip with more than two iterables
ages = [25, 30, 28]
for name, score, age in zip(names, scores, ages):
print(f”{name} | Score: {score} | Age: {age}”)
Python
# Regular for loop
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension (same result)
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With condition (filter)
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item, end=” “)
print() # New line after each row
# Output:
# 1 2 3
# 4 5 6
# 7 8 9
🕯️ Magic Note
Nested loops multiply the number of iterations. If the outer loop runs 10 times and the inner loop runs 10 times, the inner body runs 100 times. Be mindful of performance with large datasets.
Python
numbers = [1, 3, 5, 7, 9]
search_for = 4
for num in numbers:
if num == search_for:
print(f”Found {search_for}”)
break
else:
print(f”{search_for} not found”)
# Output: 4 not found
Python
# Reading a file line by line (memory efficient)
with open(“data.txt”, “r”) as file:
for line in file:
print(line.strip()) # strip removes newline
- Forgetting the colon : at the end of the for line
- Modifying a list while iterating over it (causes skipped items or errors)
- Using range(len(list)) when enumerate() would be better
- Forgetting that range() stops before the stop value
- Using for with a dictionary but expecting key-value pairs (use .items())
- Creating huge lists with list(range(1000000)) when you just need to iterate
- Write a for loop that prints each fruit in the list [“apple”, “banana”, “cherry”].
- How do you loop through a dictionary and print both keys and values?
- What does range(2, 10, 3) produce?
- Write a list comprehension that creates a list of squares for numbers 1 through 10.
- What is the difference between for item in list and for i in range(len(list))?
- How do you loop through two lists at the same time?
⚡ Whisper
The for loop is a gentle guide. It walks through your collection, one item at a time, and hands each piece to you. You do not need to count. You do not need to know the length. You just say “for each” and Python understands. This is not just a loop. It is a philosophy. Work with the data directly. Do not fight it. Do not manage indices unless you must. Let Python do the counting. You focus on what matters: what to do with each item. The for loop is patient. It will visit every item, no matter how many. It will stop when the collection ends. Trust it. Use it. It is one of the first spells you learned, and it will be one of the last you forget.