Python for beginners · Lesson 8 of 15
for loops: repeat for every item
Use a for loop to run code for every item in a list or string, count with range(), keep running totals and number items with enumerate().
Doing the same thing for every item in a list by hand would mean writing the same line again and again. A for loop loop does it for you: it takes the items one by one, puts the current one in a variable, and runs the indented block each time.
names = ["Lena", "Omar", "Yuki"]
for name in names:
print("Hello,", name)
print("Done!")Hello, Lena Hello, Omar Hello, Yuki Done!
The indented line runs three times. "Done!" is not indented, so it runs once, after the loop.
Running totals
A common pattern: create a variable before the loop, then update it inside the loop. After the loop it holds the result.
prices = [4.5, 12.0, 3.25]
total = 0
for price in prices:
total += price
print("Added", price, "- total so far:", total)
print("Total:", total)Added 4.5 - total so far: 4.5 Added 12.0 - total so far: 16.5 Added 3.25 - total so far: 19.75 Total: 19.75
Counting with range()
range() produces a series of whole numbers. range(5) gives 0, 1, 2, 3, 4: it starts at 0 and stops before 5. range(1, 6) starts at 1, and a third number sets the step. Wrap it in list() to see the numbers.
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 20, 5)))
print(list(range(5, 0, -1)))
for n in range(1, 6):
print(f"{n} x 7 = {n * 7}")[0, 1, 2, 3, 4] [1, 2, 3, 4, 5] [0, 5, 10, 15] [5, 4, 3, 2, 1] 1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
Loops with decisions inside
Anything can go inside a loop, including if. Here a loop walks through a string letter by letter and counts the a's, and another loop builds a new list with list.append().
word = "banana"
count = 0
for letter in word:
if letter == "a":
count += 1
print("Letter a:", count)
temperatures = [12, 18, 25, 31, 22]
warm_days = []
for t in temperatures:
if t > 20:
warm_days.append(t)
print("Warm days:", warm_days)Letter a: 3 Warm days: [25, 31, 22]
Numbering items with enumerate()
When you need the position as well as the item, use enumerate(). It gives you two values each round, so you write two names after for, separated by a comma. start=1 makes the counting start at 1 instead of 0.
tasks = ["wash dishes", "buy bread", "call Mia"]
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")1. wash dishes 2. buy bread 3. call Mia
for line, and indent the loop body consistently (4 spaces). A missing indent is one of the most common beginner errors.✎ Exercise
Loop over the list words and collect every word with more than 4 letters in a new list called long_words. Print the list, then print how many words it contains followed by long words.
Hint: Inside the loop, check len(w) > 4 and append the word when it is true.
words = ["sun", "planet", "moon", "galaxy", "star"]
long_words = []
# your code here
Expected output:
['planet', 'galaxy'] 2 long words
Show a solution
words = ["sun", "planet", "moon", "galaxy", "star"]
long_words = []
for w in words:
if len(w) > 4:
long_words.append(w)
print(long_words)
print(len(long_words), "long words")['planet', 'galaxy'] 2 long words
Check yourself
1. Which numbers does range(3) give?
range starts at 0 by default and stops before the number you give.
2. How many times does the body of for i in range(2, 6): run?
It runs for 2, 3, 4 and 5: four times. 6 is not included.
3. What does enumerate(["a", "b"], start=1) give you on the first round?
Each round gives the position first, then the item. With start=1, the first position is 1.