For Loops
A for loop runs a block of code once for each item in a sequence. You tell Python what you want to loop over (a list, a string, a range, etc.), and the loop does the stepping for you.
Basic syntax
for variable in sequence:
# code to run for each itemvariableis the name you choose for “the current item”sequenceis anything Python can step through (a list, string,range(), etc.)- The indented block runs once per item in the sequence
Looping with range()
range() gives you a sequence of numbers. It’s the most common way to run a loop a set number of times.
for i in range(5):
print(i)
# Output: 0 1 2 3 4range() has three common forms:
| Form | What it does |
|---|---|
range(stop) | 0 up to (not including) stop |
range(start, stop) | start up to (not including) stop |
range(start, stop, step) | start up to stop, counting by step |
for i in range(1, 6):
print(i)
# Output: 1 2 3 4 5
for i in range(0, 10, 2):
print(i)
# Output: 0 2 4 6 8range(1, 6) gives you 1 through 5, not 1 through 6. This is intentional — it matches how Python indexing works and makes it easy to write range(len(my_list)) to cover every index.
Looping over a list
If you have a list, you usually loop over the items directly (no indexes needed):
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherryYou don’t need len(fruits) here—the loop gives you each item automatically.
To modify items in the list as you go, loop over the indexes with range(len(...)) and use the index to update each item:
grades = [85, 90, 78]
for i in range(len(grades)):
grades[i] = grades[i] + 5
print(grades) # [90, 95, 83]When to use a for loop
Use a for loop when you know what you’re iterating over—a list, a range, a string, or any sequence.
If you need to keep going until a condition changes (and you don’t know how many iterations that will take), that’s a while loop. We’ll cover that next.
Summary
- A
forloop runs once per item in a sequence. range()is the go-to way to repeat something a specific number of times.