Looping Over Lists
About 15 minutes
Why this matters
The point of a list is to do something with every item: add them up, find the biggest, show them to the user. A for loop does that, and it reads almost like English.
The idea
prices = [4, 9, 2]
for price in prices:
print(price * 2)
for price in prices: runs the block once for each item, putting that item in price. No index, no range, no counter to mess up.
Python has shortcuts for common jobs:
print(sum(prices)) # 15
print(max(prices)) # 9
print(min(prices)) # 2
When you need the position as well as the item, use enumerate:
for position, price in enumerate(prices, start=1):
print(f"{position}. {price}") # 1. 4 2. 9 3. 2
Try it
Write a loop that prints every item of ["a", "b", "c"] in capitals. Then use enumerate to number them starting from 1.
Your turn
The starter reads some whole numbers from one line into a list called numbers (leave those lines alone: they use a loop you already know). Print three lines:
Total: 18
Largest: 8
Evens: 2
That is the sum, the biggest number, and how many of the numbers are even (for 5 3 8 2: total 18, largest 8, evens 2).
Recap
for item in list:visits every item in order.sum,max,minandlensummarise a list in one go.- Use a counter or an accumulator when you need something the built-ins do not do, like counting evens.
Common mistakes
- Changing the list while looping over it, such as removing items. Loop over a copy or build a new list instead.
- Looping over
len(numbers)by habit.for number in numbers:is simpler and safer. - Resetting the counter inside the loop, so it never grows.