Loops in Python

Module 3 · Loops in Python · Lesson 5 of 6

The for loop

Where a while loop repeats until a condition changes, a for loop walks through a ready-made sequence, one item at a time — and stops automatically when it runs out. No counter to manage, no condition to get wrong.

One item at a time
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
"apple""banana""cherry"
fruit
output
apple
banana
cherry

Read it almost as English: for fruit in the list, do this. Each time round, the loop variable — fruit — is set to the next item, and the indented body runs with it. A for loop will happily step through a list, the characters of a string, or a range() of numbers:

Run it yourselfruns in your browser · Python
main.py

Pairing for with range() is the classic “do this N times” pattern — and it's exactly the loop from the home page: a counter walking range(5), adding each number to a running total.

loop.pyrunning
total = 0
for i in range(5):
total += i
range(5)
0
1
2
3
4
i
total
0

Like while, a for loop can carry an else that runs when the loop finishes without a break. It's a tidy way to say “I went through everything and didn't find it”:

Run it yourselfruns in your browser · Python
main.py

Between for, while, range() and break/continue, you can now express almost any kind of repetition. A quick quiz to seal it in.