Topic 41 of 64
For with Range
Overview
Python's for loop iterates over any iterable. The range() function generates number sequences lazily, making it the standard way to run code N times or iterate over indices.
Syntax
python
# Basic range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# range(start, stop, step)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
# Countdown
for i in range(10, 0, -1): # 10, 9, ..., 1
print(i)
# Iterate over list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Common Pitfalls
- range(n) stops at n-1 — range(5) gives 0..4, not 0..5. Use range(1, n+1) for 1-indexed loops.
- Avoid modifying a list while iterating over it — use a copy or list comprehension instead.
- Interview tip: Prefer 'for item in collection' over 'for i in range(len(collection))' — it's more Pythonic. Use enumerate() when you need both index and value.
Real-World Example
Generate multiplication table using nested for loops with range
example
python
def multiplication_table(n: int) -> None:
for i in range(1, n + 1):
row = []
for j in range(1, n + 1):
row.append(f"{i * j:>4}")
print("".join(row))
multiplication_table(5)
# 1 2 3 4 5
# 2 4 6 8 10 ...