For loops and range
Overview
A for loop goes through a collection one item at a time and runs a block of code for each. It’s the loop you’ll use most often in Python — for lists, strings, files, ranges of numbers and much more.
Looping over items
fruits = ["apple", "fig", "kiwi"]
for fruit in fruits:
print(f"I like {fruit}")I like apple
I like fig
I like kiwiOn each pass, the loop variable (fruit) is set to the next item, and the block runs. When there are no more items, the loop ends. You choose the variable’s name — make it the singular of the collection: for fruit in fruits, for line in lines, for student in students.
Strings are collections of characters, so they work too:
for letter in "hey":
print(letter.upper()) # H, E, Y on separate linesrange(): looping over numbers
To repeat something a number of times, or go through a sequence of numbers, use range():
for i in range(5):
print(i) # 0 1 2 3 4range has three forms:
| Call | Numbers |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 6) |
1, 2, 3, 4, 5 |
range(0, 20, 5) |
0, 5, 10, 15 |
range(10, 0, -2) |
10, 8, 6, 4, 2 |
Just like slicing, the stop value isn’t included. range(1, 11) gives 1 to 10. That way range(n) gives exactly n numbers.
If you don’t need the number itself, the convention is to name the variable _:
for _ in range(3):
print("Hip hip hooray!")enumerate(): positions and items together
Often you need each item’s position too. Beginners write:
for i in range(len(shopping)):
print(i + 1, shopping[i])It works, but enumerate() is clearer and less error-prone:
for position, item in enumerate(shopping, start=1):
print(f"{position}. {item}")enumerate produces pairs (position, item), which the loop unpacks into two variables. start=1 counts from 1 instead of 0.
Looping over two lists together: zip()
names = ["Asha", "Ben", "Chen"]
scores = [91, 78, 85]
for name, score in zip(names, scores):
print(f"{name}: {score}")zip() pairs items up position by position, and stops at the end of the shorter list.
Building results in a loop
Combine a for loop with the counter and accumulator patterns from the previous lesson:
prices = [3.5, 12.0, 7.25]
total = 0
for price in prices:
total += price
print(total) # 22.75The next lessons show more patterns — and some built-in shortcuts like sum(prices).
Nested loops
A loop inside a loop runs the inner loop completely for each pass of the outer one:
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end="\t")
print()1 2 3
2 4 6
3 6 9Don’t change a list while looping over it
Removing items from a list while a for loop walks through it skips items in confusing ways:
numbers = [1, 2, 2, 3]
for n in numbers:
if n == 2:
numbers.remove(n) # bug: the second 2 is skipped
print(numbers) # [1, 2, 3]Instead, build a new list of the items you want to keep (Loop patterns and Comprehensions show how).
Rule of thumb: use
forwhenever you’re going through a collection or a known range of numbers; reach forwhileonly when you’re waiting for something to happen.
Times tables and a shopping list
(1) Ask for a number and print its times table from 1 to 10 in the form 7 x 3 = 21. (2) Print every even number from 2 to 20 on one line, separated by spaces, using range with a step. (3) Given a shopping list, print each item numbered from 1 (1. eggs), and finally count how many items have more than 4 letters.
# 1. Times table
n = int(input("Times table for: "))
# 2. Even numbers 2..20 on one line
# 3. Numbered shopping list + count of long items
shopping = ["eggs", "bread", "milk", "tomatoes", "tea"]# 1. Times table
n = int(input("Times table for: "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
# 2. Even numbers 2..20 on one line
for number in range(2, 21, 2):
print(number, end=" ")
print()
# 3. Numbered shopping list + count of long items
shopping = ["eggs", "bread", "milk", "tomatoes", "tea"]
long_items = 0
for position, item in enumerate(shopping, start=1):
print(f"{position}. {item}")
if len(item) > 4:
long_items += 1
print("Items with more than 4 letters:", long_items)Summary
for item in collection:runs the block once for each item, withitemset to that item.range(stop),range(start, stop)andrange(start, stop, step)produce numbers; stop is never included.for i in range(5)repeats five times, with i = 0, 1, 2, 3, 4.enumerate(items, start=1)gives positions and items together — no need forrange(len(...)).- Don’t add or remove items in a list while looping over it; build a new list instead.