A Python for loop runs a block of code once for each item in a sequence, such as a list, a string, or a range of numbers.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)This prints each fruit on its own line. On the first pass fruit is "apple", on the second it is "banana", and on the third it is "cherry". When the list runs out, the loop ends.
The syntax
for variable in iterable:
# block to repeatvariableis a name you choose. Python assigns it the next item before each pass.iterableis anything Python can step through: a list, tuple, string, dictionary, set, range, or file.- The line ends with a colon, and the block is indented by four spaces.
Unlike the for loop in C or JavaScript, there is no counter to set up, test, and increase. Python hands you the items directly.
Loop a set number of times with range()
To repeat something a fixed number of times, loop over range():
for i in range(5):
print(i)This prints 0, 1, 2, 3, and 4. range(5) produces five numbers, starting at 0 and stopping before 5.
range() accepts up to three arguments:
| Call | Produces |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 10, 2) | 0, 2, 4, 6, 8 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
The stop value is never included. To count from 1 to 10, write range(1, 11).
If you do not need the number itself, name the variable with an underscore: for _ in range(3):. It tells readers the value is not used.
Loop over a string
A string is a sequence of characters, so a for loop visits one character at a time:
vowels = 0
for letter in "programming":
if letter in "aeiou":
vowels += 1
print(vowels) # 3Get the index too with enumerate()
When you need the position as well as the item, use enumerate():
tasks = ["write", "test", "deploy"]
for index, task in enumerate(tasks, start=1):
print(index, task)1 write
2 test
3 deployenumerate() yields pairs of a counter and an item. Without start=1 the counter begins at 0.
Avoid for i in range(len(tasks)): followed by tasks[i]. It works, but enumerate() is shorter and harder to get wrong.
Loop over a dictionary
Looping over a dictionary gives you its keys. Use .items() to get each key together with its value:
prices = {"tea": 2.5, "coffee": 3.0, "juice": 4.0}
for item, price in prices.items():
print(f"{item}: {price:.2f}")tea: 2.50
coffee: 3.00
juice: 4.00Use .values() when you only need the values. More patterns are in iterating through Python collections.
Loop over two lists together with zip()
zip() pairs up items from two or more sequences:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 79]
for name, score in zip(names, scores):
print(name, score)zip() stops at the end of the shortest sequence, so no error is raised if the lists differ in length.
Build a result inside a loop
A very common pattern is to start with an empty or zero value and update it on every pass:
prices = [19.99, 5.49, 3.50]
total = 0
for price in prices:
total += price
print(round(total, 2)) # 28.98The same idea builds a new list:
names = ["ada", "grace", "linus"]
capitalized = []
for name in names:
capitalized.append(name.capitalize())
print(capitalized) # ['Ada', 'Grace', 'Linus']When the loop only builds a list like this, a list comprehension does the same job in one line: [name.capitalize() for name in names].
Stop early or skip an item
break ends the loop at once. continue skips to the next item.
for number in [3, 8, -2, 7]:
if number < 0:
print("Negative number found, stopping.")
break
print(number)This prints 3 and 8, then the message. The 7 is never reached.
The else clause on a loop
A for loop can have an else block. It runs only when the loop finishes without hitting break:
primes = [2, 3, 5, 7]
for n in primes:
if n % 2 == 0 and n > 2:
print("Found an even number above 2.")
break
else:
print("No even number above 2.")This prints No even number above 2. The feature is handy for searches, where else means "not found". Many programs never need it.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
for i in 5: | TypeError: 'int' object is not iterable | Use range(5) |
Expecting range(1, 10) to include 10 | The loop stops at 9 | Use range(1, 11) |
| Removing items from the list you are looping over | Items get skipped | Loop over a copy, or build a new list |
| Forgetting the colon | SyntaxError | End the for line with : |
| Reassigning the loop variable to change the list | The list is unchanged | Assign by index, or build a new list |
Here is the removal problem and its fix:
numbers = [1, 2, 2, 3]
# Build a new list instead of removing while looping
numbers = [n for n in numbers if n != 2]
print(numbers) # [1, 3]for or while?
Use a for loop when you are going through a collection or repeating a known number of times. Use a while loop when you repeat until a condition changes and cannot know the number of passes in advance. The overview in Python control flow compares the two side by side.
Rune AI
Key Insights
- A for loop runs its block once for every item in a list, string, dictionary, range, or other iterable.
- range(stop) counts from 0 up to, but not including, stop; range(start, stop, step) gives full control.
- Use enumerate() when you need the index and the item together.
- Use .items() to loop over the keys and values of a dictionary, and zip() to loop over two lists in step.
- break leaves the loop early and continue skips to the next item.
- Do not add or remove items from a list while looping over it; build a new list instead.
Frequently Asked Questions
How do I write a for loop in Python?
How do I loop a specific number of times in Python?
How do I get the index in a Python for loop?
How do I loop through a dictionary in Python?
Can I change a list while looping over it?
Conclusion
The for loop is the tool you will use most for repetition in Python. Loop directly over the items you care about, reach for range() when you need numbers, enumerate() when you need positions, and zip() when you need two sequences at once.
More in this topic
Nested Loops in Python
A nested loop is a loop inside another loop. See exactly what order the lines run in, how to work with grids and nested lists, and how to break out of both loops.
Python break, continue, and pass Explained
break exits a loop, continue skips to the next pass, and pass does nothing at all. See how each one works in for and while loops, and when to use them.
Python while Loops Explained
A while loop repeats a block for as long as a condition stays true. Learn the syntax, the while True pattern, how to validate input, and how to avoid infinite loops.