Loops & Iteration
Introduction to Iteration
Iteration means repeating a block of code multiple times. Without loops, you'd have to write the same code over and over. Loops automate repetition—whether you're processing 10 items or 10 million, the code stays the same. This is fundamental to programming efficiency.
Python# Without loops (tedious!) print("Hello") print("Hello") print("Hello") # With a loop (powerful!) for i in range(3): print("Hello")
For Loops: Iterating Over Collections
A 'for' loop iterates over a sequence (list, string, range, etc.) and executes the body once for each item. The loop variable takes on each value in turn. This is perfect for processing every element in a collection.
Python# Iterate over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}") # Iterate over a string for char in "Python": print(char)
The range() Function
range() generates a sequence of numbers. Use range(n) for 0 to n-1, range(start, stop) for a custom range, or range(start, stop, step) to skip values. It's memory-efficient because it generates numbers on-demand.
Python# 0 to 4 for i in range(5): print(i) # 0, 1, 2, 3, 4 # 2 to 6 for i in range(2, 7): print(i) # 2, 3, 4, 5, 6 # Even numbers: 0, 2, 4, 6, 8 for i in range(0, 10, 2): print(i)
While Loops: Condition-Based Repetition
A 'while' loop repeats as long as a condition is True. Use it when you don't know in advance how many iterations you need. Be careful: if the condition never becomes False, you get an infinite loop!
Python# Count down from 5 count = 5 while count > 0: print(count) count -= 1 # Don't forget to update! print("Liftoff!") # User input loop password = "" while password != "secret": password = input("Enter password: ")
Loop Control: break
The 'break' statement immediately exits the loop, skipping any remaining iterations. Use it to stop early when you've found what you're looking for or when a condition requires an early exit.
Python# Find first even number numbers = [1, 3, 5, 4, 7, 8] for num in numbers: if num % 2 == 0: print(f"Found even: {num}") break # Exit immediately # Output: Found even: 4
Loop Control: continue
The 'continue' statement skips the rest of the current iteration and jumps to the next one. Use it to bypass certain values without stopping the entire loop.
Python# Print only odd numbers for i in range(10): if i % 2 == 0: continue # Skip even numbers print(i) # Output: 1, 3, 5, 7, 9
Loop Control: pass
The 'pass' statement does nothing—it's a placeholder. Use it when you need a syntactically valid block but don't want to execute any code yet (e.g., stubbing out a function or loop body).
Python# Placeholder for future logic for item in items: pass # TODO: implement later # Skip certain cases explicitly for n in range(5): if n == 2: pass # Acknowledge but do nothing else: print(n)
Nested Loops
A loop inside another loop is called a nested loop. The inner loop runs completely for each iteration of the outer loop. This is essential for working with 2D data like matrices, grids, or tables.
Python# Multiplication table for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i*j}") print("---") # Traverse a 2D list matrix = [[1, 2], [3, 4], [5, 6]] for row in matrix: for cell in row: print(cell, end=" ") print()
enumerate(): Index + Value
enumerate() gives you both the index and the value in each iteration. No need to manually track counters! It returns tuples of (index, item).
Pythonfruits = ["apple", "banana", "cherry"] # Without enumerate (old way) for i in range(len(fruits)): print(f"{i}: {fruits[i]}") # With enumerate (Pythonic!) for idx, fruit in enumerate(fruits): print(f"{idx}: {fruit}")
zip(): Parallel Iteration
zip() combines multiple iterables and iterates over them in parallel. It stops when the shortest iterable is exhausted. Perfect for pairing related data.
Pythonnames = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] for name, score in zip(names, scores): print(f"{name}: {score}") # Alice: 85 # Bob: 92 # Charlie: 78
Real-World Example: Summing & Searching
Loops shine when processing data. Here's how to sum values, find maximums, and search for specific items—common tasks in any program.
Pythonnumbers = [10, 25, 8, 42, 16] # Sum all values total = 0 for n in numbers: total += n print(f"Sum: {total}") # 101 # Find maximum max_val = numbers[0] for n in numbers: if n > max_val: max_val = n print(f"Max: {max_val}") # 42
Real-World Example: Pattern Generation
Nested loops are great for generating patterns. Each outer iteration controls rows, while inner iterations control columns or repetitions.
Python# Triangle pattern for i in range(1, 6): print("*" * i) # * # ** # *** # **** # ***** # Number pyramid for i in range(1, 5): for j in range(1, i + 1): print(j, end="") print()
Performance & Best Practices
1) Avoid infinite loops—always ensure the condition eventually becomes False. 2) Use 'for' when you know the iterations; use 'while' for unknown counts. 3) Prefer list comprehensions for simple transformations. 4) Don't modify a list while iterating over it—use a copy instead.
Python# BAD: Modifying while iterating items = [1, 2, 3, 4] # for item in items: # items.remove(item) # Bug! # GOOD: Iterate over a copy for item in items[:]: items.remove(item) # BEST: Use comprehension for filtering original = [1, 2, 3, 4, 5] odds = [x for x in original if x % 2 != 0]
Master this concept
Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.