For Loops
Process a list of email addresses. Analyze each line in a log file. Generate multiplication tables. Calculate statistics across datasets. Render pixels in an image.
Every one of these tasks requires doing the same operation repeatedly—just with different data each time. That's what for loops enable: systematic iteration over collections.
Computers excel at repetition without fatigue or error. For loops are how you harness that power in Python.
What is a For Loop?
A for loop executes a block of code once for each item in a sequence (list, string, range, etc.):
| Basic For Loop Structure | |
|---|---|
- The loop variable (
item) takes on each value from the sequence in order
Here's a concrete example:
| Iterating Over a List | |
|---|---|
languagebecomes "Python", then "JavaScript", then "Go" on successive iterations
Output:
Why For Loops Matter
For loops solve a fundamental problem: applying operations across collections without writing repetitive code. This is computational thinking in action—decomposing a large task (process 1000 items) into a simple, repeatable pattern (process one item, repeat).
Without loops, processing three items requires three nearly-identical code blocks:
| Without Loops (Don't Do This) | |
|---|---|
With loops, one block handles any number of items:
- Works for 3 items, 300 items, or 3 million items
Loops make your code:
- Scalable: Works with any collection size
- Maintainable: Change the logic once, not N times
- Readable: Expresses intent clearly
Looping Over Different Sequences
Lists
The most common use case—iterate over list elements:
| Processing List Items | |
|---|---|
- Each iteration,
scoretakes on the next value from the list (85, then 92, then 78, etc.)
Strings
Strings are sequences of characters, so you can loop over them:
- Each character becomes the loop variable in turn
Output:
Dictionaries
Loop over dictionary keys, values, or both:
| Dictionary Iteration | |
|---|---|
.keys()returns the dictionary keys—actually the default behavior.values()returns just the values.items()returns tuples of(key, value)pairs—note we unpack into two variables
Output of .items() loop:
Dictionary Unpacking
for key, value in user.items() uses tuple unpacking. Each iteration, .items() returns a tuple like ("name", "Alice"), which Python automatically unpacks into the two variables.
The range() Function
Need to repeat an action exactly N times? Generate a sequence of IDs? Count from 1 to 100? The range() function generates number sequences for counted loops:
range(5)generates numbers from 0 to 4 (not including 5)
Output:
Off-By-One Trap
range() stops before the end value. range(10) generates 0-9, not 1-10. This is Python's most common off-by-one error.
Range with Start and Stop
Skip header rows when processing files. Process items 10-20 from a dataset. Generate IDs starting from a specific number:
range(start, stop)goes from start (inclusive) to stop (exclusive)
Output:
Range with Step
Process every other row in a spreadsheet. Sample data (take every 100th record). Generate sequences like even numbers or multiples of 5:
range(start, stop, step)increments by step each time
Output:
Counting Backwards
Countdown timers. Processing undo stack (most recent first). Reverse iteration when building output in reverse order:
- Start at 10, stop before 0, decrement by 1
Output:
Looping with Indices: enumerate()
Displaying numbered lists ("1. First item, 2. Second item..."). Tracking position while processing. Comparing items to their neighbors by index. When you need both the value and its position, enumerate() provides both:
| Enumerate for Index and Item | |
|---|---|
enumerate()yields tuples of(index, item)which we unpack
Output:
Start counting from 1 instead of 0:
| Enumerate with Custom Start | |
|---|---|
start=1makes the index begin at 1 instead of 0
Output:
Nested Loops
Multiplication tables. Processing 2D grids (chess boards, images, spreadsheets). Comparing every item with every other item. Nested loops handle multidimensional problems:
| Nested Loops | |
|---|---|
- Outer loop runs 3 times
- For each outer iteration, inner loop runs 3 times (total: 3 × 3 = 9 iterations)
Output:
Performance Warning
Nested loops multiply execution time. Two loops of 100 items each = 10,000 iterations. Three loops of 100 = 1,000,000 iterations. Be mindful with large datasets.
Looping Over Multiple Sequences: zip()
Combining first names with last names. Matching products with prices. Processing parallel lists of data. When you have related data in separate lists, zip() pairs them element-by-element:
| Zipping Sequences | |
|---|---|
zip()pairs corresponding elements: ("Alice", 30), ("Bob", 25), ("Charlie", 35)
Output:
If sequences differ in length, zip() stops at the shortest:
| Zip Stops at Shortest | |
|---|---|
- Only 2 pairs are created because
bhas only 2 elements
Output:
Practical Patterns
Accumulating Values
Calculate totals from transactions. Count how many items match a criterion. Find the maximum value. Track a running average:
| Summing a List | |
|---|---|
- Initialize the accumulator variable to 0 before the loop starts
- Add each number to the accumulator on each iteration (final result: 100)
Building New Lists
Apply tax to prices. Convert temperatures from Celsius to Fahrenheit. Extract specific fields from records. Generate derived data:
| Transforming List Values | |
|---|---|
- Create an empty list to hold the results before the loop
- Calculate the new value (price plus 13% tax) and append it to the results list
List Comprehensions
Python has a more concise syntax for this pattern called list comprehensions. See the Comprehensions article for details.
Filtering Data
Remove invalid email addresses. Find all orders above $100. Separate active from inactive users. Extract matching search results:
| Finding Specific Items | |
|---|---|
- Only append items that meet the condition
For vs While Loops
Python has two types of loops:
- For loops: "Do this for each item" (iteration over known sequences)
- While loops: "Do this until condition becomes false" (iteration until something happens)
Use for loops when you know what you're iterating over:
- We know we want exactly 10 iterations
Use while loops when you don't know how many iterations you need:
| While Loop (Unknown Count) | |
|---|---|
- Loop until user types "quit"—we don't know how many iterations that takes
See While Loops for more on while loops.
Common Pitfalls
Modifying a List While Iterating
Don't modify a list you're currently iterating over:
| Dangerous: Modifying During Iteration | |
|---|---|
- ⚠️ Don't do this! Modifying the list during iteration causes elements to be skipped—a subtle and dangerous bug
Solution: Iterate over a copy or build a new list:
| Safe: Building New List | |
|---|---|
- Iterate over original, build new list—safe and clear
Range Off-By-One Error
- Prints 0-9, not 1-10!
range(10)generates 0, 1, 2, ..., 9 (stops before 10)
To iterate from 1 to 10:
- Start at 1, stop before 11 (so last value is 10)
Practice Problems
Practice Problem 1: Basic Iteration
Write a for loop that prints each character in the string "Python" on a separate line.
Practice Problem 2: Range Usage
What does this code print?
Practice Problem 3: Enumerate
How would you print each item in fruits = ["apple", "banana", "cherry"] with its position number starting from 1?
Practice Problem 4: Accumulation
Write a loop that calculates the product of all numbers in [2, 3, 4, 5].
Key Takeaways
| Concept | What It Means |
|---|---|
| For loop | Execute code once for each item in a sequence |
range() |
Generate sequences of numbers: range(start, stop, step) |
enumerate() |
Get both index and item: for i, item in enumerate(seq) |
zip() |
Pair elements from multiple sequences |
| Loop variable | Takes on each value from the sequence in turn |
| Nested loops | Loops inside loops—useful for multidimensional data |
Further Reading
- Python For Loops Tutorial - Official Python documentation
- Itertools Module - Advanced iteration tools
- List Comprehensions - More concise syntax for common loop patterns
- While Loops - Loops based on conditions rather than sequences
For loops are one of the first control structures you'll learn, and one you'll use daily. They transform repetitive manual work into systematic, scalable operations. Master iteration—over lists, strings, ranges, and dictionaries—and you can process any collection Python throws at you.
Every complex program is built on simple loops. Learn to write them well.