For loops and range()
Repeat code for every item or a set number of times
A for loop runs the same block of code once for every item in a collection. Use it when you know what you want to go through: every letter, every list item, or every number from 1 to 10.
How a for loop works
for fruit in ["apple", "banana", "cherry"]:
print(fruit)forstarts the loop.fruitis the loop variable. It holds the current item and changes every round.in [...]is the collection to walk through.- The colon
:and the indented lines below it form the loop body.
for student in students, for word in words. It makes the code read like English.The range() function
When you want to repeat something a number of times, or need a sequence of numbers, use range(). It has three forms.
| Feature | Produces | Meaning |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | stop |
| range(2, 6) | 2, 3, 4, 5 | start, stop |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | start, stop, step |
| range(5, 0, -1) | 5, 4, 3, 2, 1 | counting down |
Repeat N times
for i in range(3):
print("Hello!")
# Hello! is printed 3 times (i is 0, 1, 2)Start and stop
for number in range(1, 6):
print(number)
# 1 2 3 4 5 (6 is not included)Using a step
for even in range(0, 11, 2):
print(even)
# 0 2 4 6 8 10
for n in range(5, 0, -1):
print(n)
print("Lift off!")
# 5 4 3 2 1 Lift off!range(1, 5) stops at 4. To include 5, write range(1, 6). This "off by one" mix-up is the most common range() mistake.Looping through different collections
Strings
for letter in "AI":
print(letter)
# A
# ILists
scores = [72, 88, 95]
total = 0
for score in scores:
total = total + score
print(f"Total: {total}") # Total: 255
print(f"Average: {total / len(scores)}") # Average: 85.0Dictionaries
Looping over a dictionary gives you its keys. Use .items() to get each key and value together.
prices = {"coffee": 3.5, "tea": 2.0, "cake": 4.25}
for item in prices:
print(item) # coffee, tea, cake
for item, price in prices.items():
print(f"{item}: ${price}") # coffee: $3.5 ...Getting the position with enumerate()
Sometimes you need both the item and its position. enumerate() gives you both, so you don't have to keep a counter yourself.
tasks = ["write code", "test it", "ship it"]
for index, task in enumerate(tasks, start=1):
print(f"{index}. {task}")
# 1. write code
# 2. test it
# 3. ship itBuilding a new list in a loop
A very common pattern: start with an empty list and append() to it inside the loop.
names = ["ana", "ben", "chen"]
capitalized = []
for name in names:
capitalized.append(name.title())
print(capitalized) # ['Ana', 'Ben', 'Chen']Loops with if statements
numbers = [3, 8, 12, 5, 20]
for n in numbers:
if n > 10:
print(f"{n} is big")
else:
print(f"{n} is small")Nested loops
You can put a loop inside another loop. The inner loop runs completely for every single round of the outer loop.
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print() # new line after each row
# 1 2 3
# 2 4 6
# 3 6 9print(..., end=" ") prints a space instead of starting a new line, so the values stay on one row.Common mistakes
- Forgetting the colon at the end of the
forline. - Forgetting to indent the loop body, or indenting the line after the loop by accident (then it runs every round).
- Expecting
range(1, 10)to include 10. - Changing a list (adding or removing items) while you loop over it. Loop over a copy, or build a new list instead.
What's next?
for loops are perfect when you know what to loop over. When you don't know how many times to repeat, use a while loop.