After this lesson you can repeat an action for every item in a collection, and count a fixed number of times. The for loop is the one you will write most often in Python.
Looping over a list
A list is written with square brackets. A for loop takes one item at a time and runs its block once for each:
products = ["notebook", "pen", "stapler"]
for product in products:
print("In stock:", product)In stock: notebook
In stock: pen
In stock: staplerThe name after for (product) is a loop variable. Python gives it the first item, runs the block, then gives it the next item, and so on until the list is used up. You choose the name. A good habit is to use the singular of the collection's name, product for products.
There is no counter to set up or update. Python manages that for you, which is why for loops are shorter and safer than while loops for this job.
Looping over a string
A string is a sequence of characters, so a for loop works on it as well:
for letter in "shop":
print(letter)s
h
o
pCounting with range()
To repeat something a certain number of times, use range(). With one number it counts from 0 up to, but not including, that number:
for number in range(4):
print(number)0
1
2
3Starting at 0 and stopping early feels odd at first, but it means that range(4) gives exactly four numbers. You can see them as a list with the list function:
print(list(range(4)))[0, 1, 2, 3]With two numbers, the first is where to start and the second is where to stop:
for day in range(1, 6):
print("Day", day)Day 1
Day 2
Day 3
Day 4
Day 5With three, the third is the step, the amount added each time. Steps can be negative to count down:
print(list(range(0, 20, 5)))
print(list(range(10, 0, -2)))[0, 5, 10, 15]
[10, 8, 6, 4, 2]In each case the stop value is not included.
Totals with for
Running totals work just as they did with while, but with less setup:
prices = [40, 25, 60, 15]
total = 0
for price in prices:
total += price
print("Total:", total)
print("Items:", len(prices))Total: 140
Items: 4Using the position as well
Sometimes you need the position of each item as well as the item. Python's enumerate() gives you both:
queue = ["Asha", "Ben", "Chloe"]
for position, name in enumerate(queue, start=1):
print(position, name)1 Asha
2 Ben
3 ChloeWithout start=1 the numbering begins at 0, which is how Python counts positions internally.
Looping a fixed number of times
If you do not need the loop variable, you can still use range to repeat something. A common convention is to name the unused variable with an underscore:
for _ in range(3):
print("Beep")Beep
Beep
Beepfor or while?
Choose by asking one question: do I know what I am looping over?
- for: a list, a string, a range of numbers, anything you can go through item by item.
- while: repeating until something happens, where you cannot tell in advance how many times.
When both would work, for is usually simpler and has fewer ways to go wrong.
Changing a list while looping
Be careful not to add or remove items from the same list you are looping over, because this can skip items in surprising ways. Build a new list instead. Lists have their own lessons later.
Why Python loops over items directly
In some languages you must write a loop that counts positions and then reach into a list using each position. Python lets you skip that step and take the items themselves. That removes a whole category of mistakes, such as counting one too far and running off the end of the list.
It also makes the code read like what you mean: "for each product in the products". When you do need positions, enumerate gives them without extra bookkeeping.
A practical tip: when you are unsure what a loop is doing, add a temporary print of the loop variable as the first line of the block. Seeing the values arrive one by one often solves the puzzle at once. Remove the line when you are done so the output stays clean.
Common mistakes
- Forgetting that range stops early.
range(5)ends at 4. For 1 to 5 writerange(1, 6). - Missing colon or indentation.
for item in items:needs a colon and an indented block. - Looping over a number.
for i in 5:fails because 5 is not a sequence. Userange(5). - Using the wrong loop variable inside the block. If you write
for product in products:then useproduct, notproducts, inside the block. - Using a name that is already important. After
for total in prices:the variabletotalhas been overwritten by the loop.
Here is the error from looping over a plain number:
for i in 5:
print(i)TypeError: 'int' object is not iterableExercise
Print a times table: the first five multiples of 7 as lines like 7 x 1 = 7. Then compute the sum of all the whole numbers from 1 to 100.
Show one possible answer
for n in range(1, 6):
print(f"7 x {n} = {7 * n}")
total = 0
for n in range(1, 101):
total += n
print("Sum of 1 to 100:", total)7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Sum of 1 to 100: 5050The second loop uses 101 as the stop value so that 100 is included.
Next: steering a loop with break, continue and the loop else.
Key points
- A for loop runs its block once for each item in a sequence, such as a list or a string.
- range(stop) counts from 0 up to, but not including, stop. range(start, stop, step) gives more control.
- Use for when you know what to loop over, and while when you loop until a condition changes.
- enumerate() gives you the position and the item together.