For Loops
A for loop repeats a block of code once for every item in a sequence, such as each letter of a word, each number in a range or each name in a list. It is the loop you'll use most often in Python.
Looping through a list
A list is an ordered collection of values written inside square brackets, separated by commas. (Lists get their own page in the next chapter: Lists.) A for loop visits each item in turn:
subjects = ["Maths", "English", "Biology"]
for subject in subjects:
print("Revise", subject)
print("Revision plan done")
On each pass (called an iteration), the loop variable subject takes the next value from the list, and the indented block runs once. When the items run out, the loop ends. You choose the loop variable's name; pick one that describes a single item.
Looping a set number of times with range()
range() produces a sequence of whole numbers. It has three forms:
range(stop): from 0 up to, but not including,stop.range(start, stop): fromstartup to, but not including,stop.range(start, stop, step): counting in steps ofstep, which can be negative.
for i in range(3):
print("Attempt", i + 1)
To see all the numbers a range produces at once, convert it to a list:
print(list(range(5))) print(list(range(1, 6))) print(list(range(2020, 2031, 5))) print(list(range(10, 0, -2)))
Expecting range() to include the stop value. range(1, 5) gives 1, 2, 3 and 4, but not 5. To count from 1 to 10, write range(1, 11).
Looping through a string
A string is a sequence of characters, so a for loop can visit each one. This program counts the vowels in a word:
word = "Mombasa"
vowels = 0
for letter in word:
if letter.lower() in "aeiou":
vowels += 1
print(word, "has", vowels, "vowels")
Accumulating results
A very common pattern is to set up a variable before the loop and update it on every iteration. This is called an accumulator.
expenses = [350, 1200, 80, 2500] # in KES
total = 0
for amount in expenses:
total += amount
print(f"Total spent: KES {total}")
total_1_to_100 = 0
for n in range(1, 101):
total_1_to_100 += n
print(total_1_to_100)
The same pattern finds the largest value: keep track of the best so far and replace it when you see something bigger.
scores = [72, 85, 64, 90, 58]
highest = scores[0] # start with the first score
for score in scores:
if score > highest:
highest = score
print("Highest score:", highest)
(Python's built-in sum() and max() do these two jobs for you, but writing the loop yourself teaches the pattern behind them.)
Getting the position with enumerate()
enumerate() gives you each item together with its position. Use start=1 to count from 1 instead of 0.
tasks = ["Wake up", "Gym", "Study"]
for number, task in enumerate(tasks, start=1):
print(number, task)
Looping over two lists together with zip()
zip() pairs up items from two (or more) sequences, so you can loop over them side by side.
names = ["Amina", "Brian", "Chebet"]
scores = [78, 64, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")
If the sequences have different lengths, zip() stops at the end of the shortest one.
After a for loop finishes, the loop variable keeps the last value it was given. After the subjects loop above, subject still holds "Biology". Avoid relying on this; it makes code harder to follow.
Adding or removing items from a list while looping over that same list. The loop can skip items or behave unexpectedly. Loop over a copy instead, or build a new list, as shown on the Comprehensions page.
Key points
for item in sequence:runs the block once per item in a list, string or range.range(start, stop, step)produces numbers up to, but not including,stop.- Accumulator variables collect totals, counts and maximums across a loop.
enumerate()adds positions;zip()walks several sequences together.- Use break and continue for finer control of a loop (that's the next page).
Tip: use the ← and → keys to move between pages.
