Python for Loops
1Python for Loops: overview
A for loop runs the same block of code once for every item in a collection, giving the current item a name while its turn runs.
Before this lesson: Python Variables, Python if, elif and else
2Python for Loops: diagram
3Python for Loops: explained step by step
A for loop lets you write an action once and have Python repeat it for every item in a collection. You don't need to keep a counter or decide when to stop: the loop ends by itself when it runs out of items.
for name in ["Asha", "Ben", "Chen"]:
print("Hello,", name)
print("Everyone greeted")The line ending in a colon is the loop header. The indented lines under it form the loop body. Each pass through the body is called an iteration, and on each one the loop variable (name here) holds the current item. The unindented print runs once, after the loop has finished.
What can you loop over?
Anything Python can hand out one piece at a time, called an iterable: lists, tuples, strings (one character at a time), dictionaries, sets, files and range().
Counting with range()
When you want to repeat something a set number of times, or you need the numbers themselves, use range(). range(3) produces 0, 1, 2: it stops before the end value, just like slicing does. range(1, 6) gives 1 to 5, and a third argument sets the step.
for i in range(3):
print("Round", i)
for n in range(10, 0, -3):
print(n)Index and item together: enumerate()
If you need each item's position too, wrap the collection in enumerate(). It gives you (index, item) pairs that you unpack straight into two variables. Pass start=1 when you want human-friendly numbering. This is clearer and safer than juggling range(len(items)) and indexes by hand.
break and continue
break stops the loop immediately, which is useful once you've found what you were searching for. continue skips the rest of the body for the current item and moves on to the next one.
readings = [18, 21, -1, 25, 40, 19]
for t in readings:
if t == -1:
continue # faulty sensor value: skip it
if t > 35:
print("Too hot, stopping at", t)
break
print("OK:", t)The accumulator pattern
A very common job is to combine all the items into one result: a total, a count, the longest word. Create the result variable before the loop, update it inside the loop, and use it after the loop. You'll see this pattern in nearly every program you write.
Quick reference: Python for Loops
- Python Control Flow Cheat Sheet: if, for, while, match — Python control flow uses `if`/`elif`/`else` to choose, `for` and `while` to repeat, `break` and `continue` to…
- Python break vs continue vs pass: Differences — `break` stops the whole loop, `continue` skips the rest of the current iteration and moves to the next one, a…
- How to Loop Through a Dictionary in Python — Use `for key, value in my_dict.items():` to loop over keys and values together. Loop over `my_dict` (or `.key…
- Python Program for Linear Search (with Examples) — Linear search checks every item of a list from left to right and returns the index of the first match, or `-1…
- Python Program to Find the Largest Number in a List — The largest number in a list is `max(numbers)`. To do it by hand, start with the first item and replace it wh…
- Python Program to Check Prime Number — A prime number is a whole number greater than 1 that has no divisors other than 1 and itself; in Python you t…
- Python Program to Count Vowels in a String — To count vowels in Python, loop over the lowercase string and count the characters found in `"aeiou"`: `sum(1…
- Python Program to Find Factorial of a Number — The factorial of n (written n!) is the product of all whole numbers from 1 to n, and in Python you can comput…
4Python for Loops: syntax
for item in iterable:
# body: runs once per item
for i in range(stop): # 0, 1, ..., stop - 1
for i in range(start, stop, step):
for index, item in enumerate(items, start=1):
break # leave the loop right now
continue # skip to the next item
5Python for Loops: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
scores = [72, 95, 58, 88, 64]
total = 0
for score in scores:
total += score
print("Average:", total / len(scores))
for position, score in enumerate(scores, start=1):
if score < 60:
print(f"Student {position} needs help ({score})")
continue
print(f"Student {position} passed ({score})")
for score in scores:
if score >= 90:
print("First top score found:", score)
breakExpected outputAverage: 75.4
Student 1 passed (72)
Student 2 passed (95)
Student 3 needs help (58)
Student 4 passed (88)
Student 5 passed (64)
First top score found: 95
7Python for Loops: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1A list of five test scores is stored in
scores. - Line 3The accumulator
totalstarts at 0 before the loop, so it is created only once. - Line 4-5The loop runs five times. Each time,
scoreholds the next value and gets added tototal, which ends at 377. - Line 6This line is not indented, so it runs once, after the loop: 377 / 5 = 75.4.
- Line 8
enumerate(scores, start=1)hands out pairs like(1, 72), unpacked intopositionandscore. - Line 9-11For a score under 60, a help message is printed and
continuejumps straight to the next student, skipping line 12. - Line 12Every student who did not hit
continuegets the "passed" line. - Line 14-17The last loop searches for the first score of 90 or more. It finds 95 on the second item, prints it, and
breakends the loop without checking the rest.
8Python for Loops: common mistakes
Expecting range() to include the end value
✗ Wrong
for day in range(1, 7):
print("Day", day)✓ Right
for day in range(1, 8):
print("Day", day)range() stops just before the end value. To count from 1 to 7, the end must be 8.
Resetting the total inside the loop
✗ Wrong
prices = [5, 10, 15]
for p in prices:
total = 0
total += p
print(total)✓ Right
prices = [5, 10, 15]
total = 0
for p in prices:
total += p
print(total)Create the accumulator once, before the loop. Only the update belongs inside the body.
Changing the loop variable to change the list
✗ Wrong
prices = [10, 20, 30]
for p in prices:
p = p * 2
print(prices)✓ Right
prices = [10, 20, 30]
for i, p in enumerate(prices):
prices[i] = p * 2
print(prices)The loop variable is just a name for the current item. Giving it a new value doesn't touch the list. Use enumerate() to get the index and assign to prices[i] (or build a new list).
9Python for Loops: exercises
Write your answer, then press Check. The checks run in your browser.
1. Add up the cart
Write code Easy ✓ CompletedUse a for loop (not sum()) to add up all the prices in prices. Store the result in total, then print it.
prices = [12.5, 3.0, 7.25, 20.0]
total = 0
# loop over prices and add each one to total
prices = [12.5, 3.0, 7.25, 20.0]
total = 0
for price in prices:
total += price
print(total)
2. Predict break and continue
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
for n in range(1, 10):
if n == 7:
break
if n % 2 == 0:
continue
print(n)
print("done")1
3
5
done
2 more exercises → 4 more examples
Questions learners ask
When should I use a for loop instead of a while loop?
Use a for loop when you know what you are looping over: the items of a collection or a fixed number of repetitions. Use a while loop when you must keep going until some condition changes and you can't tell in advance how many rounds that will take.
How do I get the index in a Python for loop?
Wrap the collection in enumerate(): for i, item in enumerate(items): gives you the position and the item together. Add start=1 if you want counting to begin at 1.
Why does range(5) stop at 4?
range() stops just before its end value, so range(5) gives exactly five numbers: 0, 1, 2, 3, 4. Those are also the valid indexes of a five-item list, which is why this convention is so handy.
Further reading
10Next lesson
Up nextPython while LoopsA while loop keeps repeating a block of code for as long as its condition is True, checking the condition again before …Related:
Python range() FunctionPython break and continuePython enumerate() and zip()Python Lists
← Python match Statement · All Control Flow lessons · Practise in the IDE