Loops and Iteration
Master repetition in Python using while loops for condition-driven repetition, for loops for sequence iteration, range() generators, enumerate(), and zip().
Imagine being asked to write “I will practice coding every day” 1,000 times on a physical chalkboard. Your hand would cramp, your chalk would snap, and you would quickly lose count.
Computers, on the other hand, exist to perform repetitive tasks with unwavering accuracy at lightning speed. A computer can repeat a calculation one thousand times—or one billion times—without getting tired, bored, or making a clerical error.
In programming, this ability to repeat a block of code multiple times is called Iteration or Looping.
Python provides two primary loop mechanisms:
- The
whileLoop: Runs as long as a specified condition remainsTrue(condition-driven). - The
forLoop: Runs once for every item in a collection or sequence (collection-driven).
1. The while Loop: Condition-Driven Repetition
A while loop checks a condition using operators. If the condition evaluates to True, Python executes the indented block of code. Once it reaches the bottom of the block, Python jumps right back up to the top and checks the condition again.
This cycle continues until the condition finally becomes False:
countdown = 5
while countdown > 0:
print(f"T-minus {countdown} seconds...")
countdown -= 1 # Crucial: decrease countdown by 1 each time
print("Liftoff! Rocket launched successfully.")
Output:
T-minus 5 seconds...
T-minus 4 seconds...
T-minus 3 seconds...
T-minus 2 seconds...
T-minus 1 seconds...
Liftoff! Rocket launched successfully.
The Three Essential Components of a while Loop
Every functional while loop requires three distinct parts:
- Initialization: Set up a starting state or variable before the loop begins (
countdown = 5). - Evaluation: The condition that Python evaluates before every single repetition (
countdown > 0). - Progression: An update inside the loop that moves the state toward making the condition
False(countdown -= 1).
The Dreaded “Infinite Loop” Trap
What happens if you forget step 3 (Progression)?
count = 1
# DANGER: Infinite loop!
while count <= 5:
print(count)
# Forgot: count += 1!
Because count remains 1 forever, count <= 5 will never become False. Python will print 1 millions of times per second until your CPU fan spins loudly, your terminal freezes, or you press Ctrl + C to terminate the script!
[!CAUTION] Always verify that your
whileloop includes a clear, guaranteed path to termination.
2. The for Loop: Collection-Driven Iteration
While other programming languages like C, Java, or C++ historically used numeric counters for loops (for (int i=0; i<10; i++)), Python took a much more elegant approach.
In Python, a for loop is fundamentally a for-each loop. It steps through each item in a sequence or collection one by one, automatically assigning each item to a loop variable:
Iterating Over a String:
Strings are sequences of characters (as explored in strings). A for loop visits every character in order:
word = "Python"
for letter in word:
print(f"Character: {letter}")
Output:
Character: P
Character: y
Character: t
Character: h
Character: o
Character: n
Iterating Over a List:
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(f"I enjoy eating a fresh {fruit}.")
Output:
I enjoy eating a fresh Apple.
I enjoy eating a fresh Banana.
I enjoy eating a fresh Cherry.
Notice how clean this is:
- No manual index counting (
i = 0). - No boundary checking (
i < len(fruits)). - No manual incrementing (
i += 1). Python handles all iteration mechanics automatically behind the scenes!
3. The range() Function: Generating Numeric Sequences
What if you just want to run a piece of code a fixed number of times—say, exactly 5 times?
Python provides the built-in range() function. range() generates an immutable sequence of numbers on demand without allocating memory for all numbers up front.
Form 1: range(stop)
Generates integers starting at 0 up to, but not including, stop:
for i in range(4):
print(f"Iteration number: {i}")
Output:
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
[!IMPORTANT] Just like string slicing in strings,
range()is half-open: the stop boundary is exclusive.range(4)yields 0, 1, 2, and 3 (four numbers total). It does not include 4!
Form 2: range(start, stop)
Specify custom starting and stopping values:
for page in range(1, 4):
print(f"Reading chapter page {page}...")
Output:
Reading chapter page 1...
Reading chapter page 2...
Reading chapter page 3...
Form 3: range(start, stop, step)
Specify the step size (stride) to jump numbers or count backwards:
# Even numbers between 2 and 10:
for even in range(2, 11, 2):
print(even, end=" ")
print()
# Countdown from 5 down to 1:
for tick in range(5, 0, -1):
print(tick, end=" ")
print("Boom!")
Output:
2 4 6 8 10
5 4 3 2 1 Boom!
4. enumerate(): Accessing Both Index and Value
A very common beginner mistake is using range(len(...)) when needing both the position and the value:
# The clumsy anti-pattern (avoid this!):
languages = ["Python", "JavaScript", "Rust"]
for i in range(len(languages)):
print(f"{i + 1}. {languages[i]}")
The idiomatic, professional Python approach is using the built-in enumerate() function. It wraps your collection and yields a pair: (index, item) on every step:
languages = ["Python", "JavaScript", "Rust"]
for index, lang in enumerate(languages, start=1):
print(f"{index}. {lang}")
Output:
1. Python
2. JavaScript
3. Rust
Setting start=1 tells enumerate to begin counting from 1 instead of 0, perfect for human-readable numbered lists!
5. Parallel Iteration with zip()
When you have two or more related lists and want to loop through them side-by-side, use the built-in zip() function:
students = ["Alice", "Bob", "Charlie"]
scores = [92, 88, 95]
for student, score in zip(students, scores):
print(f"{student} scored {score}% on the midterm exam.")
Output:
Alice scored 92% on the midterm exam.
Bob scored 88% on the midterm exam.
Charlie scored 95% on the midterm exam.
6. Nested Loops: Loops Inside Loops
You can place loops inside other loops. The inner loop executes all its iterations for every single cycle of the outer loop:
# Generate a mini 3x3 multiplication table
for row in range(1, 4):
for col in range(1, 4):
product = row * col
print(f"{product:2d}", end=" ")
print() # Print a newline at the end of each row
Output:
1 2 3
2 4 6
3 6 9
[!WARNING] Be mindful with nested loops! If an outer loop runs 1,000 times and an inner loop runs 1,000 times, the inner block runs $1,000 \times 1,000 = 1,000,000$ (one million) times. Excessive nesting can quickly degrade program performance.
7. When to Use while vs for
| Use Case | Recommended Loop | Reason |
|---|---|---|
| Fixed count (e.g., repeat 10 times) | for _ in range(10): | Predictable, automatic termination |
| Iterating collections (lists, strings, dicts) | for item in collection: | Direct access, clean and Pythonic |
| Waiting for user input | while True: / while not valid: | Number of attempts is unpredictable |
| Game loop or event loop | while is_running: | Keeps updating state until user quits |
| Polling external APIs / network sockets | while not connected: | Loops until external condition changes |
Summary & Practice
- Use
whileloops when repetition is governed by a dynamic condition. Always verify the progression step to avoid infinite loops. - Use
forloops to iterate directly over sequences (strings, lists, ranges). - Use
range(start, stop, step)to generate numeric intervals. - Use
enumerate(seq)when you need both the index and the item. - Use
zip(seq1, seq2)to pair up multiple iterables simultaneously.
Now that you understand the rhythm of loops, learn how to jump out early, skip iterations, or run post-loop cleanup blocks in loop-control.