The for Loop and range()
📂 Phase 2: Loops, Conditional Statements, Functions (Days 6–10) · Python ProgrammingA for loop in Python repeats a block of code once for every item in a sequence — a list, a string, or a range of numbers. Python has no traditional C-style for loop with a counter, condition, and increment all in one line; instead, it always iterates directly over a sequence of values.
Iterating Over a Sequence Directly
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
This is effectively what other languages call a "for-each" loop — Python does not have a separate keyword for it, because the regular for loop already works this way by default.
The range() Function
When you need to repeat something a fixed number of times rather than iterating over an existing collection, range() generates a sequence of numbers on demand.
for i in range(5):
print(i)
# 0 1 2 3 4 — start is inclusive (0), stop is EXCLUSIVE (5)
| Form | Meaning | Example Output |
|---|---|---|
| range(stop) | 0 up to (not including) stop | range(5) → 0,1,2,3,4 |
| range(start, stop) | start up to (not including) stop | range(2, 6) → 2,3,4,5 |
| range(start, stop, step) | start to stop, counting by step | range(0, 10, 2) → 0,2,4,6,8 |
The stop value is always exclusive — range(0, 10) produces 10 numbers (0 through 9), never including 10 itself. This is consistent with how string and list slicing behave too.
Counting Backward
for i in range(10, 0, -1):
print(i)
# Counts down: 10, 9, 8, ... 1
Iterating Over a String
word = "Python"
for letter in word:
print(letter)
# P y t h o n — printed one character per line
Using enumerate() to Get the Index Too
When you need both the position and the value while looping, enumerate() is the idiomatic Python way — far cleaner than manually tracking an index variable.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
# 2 cherry
Looping with an Index the "Old" Way (and Why to Avoid It)
# Works, but not idiomatic Python
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(fruits[i])
# Preferred — direct iteration, cleaner and less error-prone
for fruit in fruits:
print(fruit)
The for-else Clause — Unique to Python
A for loop can have an else block that runs only if the loop completed without hitting a break — useful for "search and report not found" logic.
numbers = [4, 8, 15, 16]
for n in numbers:
if n == 7:
print("Found 7!")
break
else:
print("7 was not found in the list")
# Output: 7 was not found in the list
Interview tip: A common question is "Why doesn't Python have a do-while loop?" — Python deliberately omits it; the same effect is achieved with a while True loop combined with a break condition checked inside the loop body, which is considered more readable in Python's philosophy.