Looping over a list
🌍 In real life. At the start of class, the teacher reads every name on the register, top to bottom, once each. At the end of term, they go down the marks column adding them up, or looking for the highest. Each job visits every item once, in order.
A for loop does exactly that with a list.
The idea in one sentence: for item in my_list: visits every item of the list in order, putting each one in the loop variable, so you can print it, add it up, or keep it.
Its words:
for item in my_list:: the sameforloop you used withrange()and stringssum(),min(),max(): ready-made helpers that walk a list of numbers for you- filtering: building a new list that keeps only the items you want
.split(): cuts text into a list of words
Step by step, for the names below:
namegets"Ana", and the block prints Hi Ana.namegets"Bo", then"Cy", and the block runs for each.- No items are left, so the loop ends.
names = ["Ana", "Bo", "Cy"]
for name in names:
print("Hi", name)For lists of numbers, Python has ready-made helpers: sum() adds them all, and min() and max() find the smallest and the largest. The average is sum(...) / len(...).
scores = [7, 9, 4, 10]
print(sum(scores))
print(min(scores), max(scores))
print(sum(scores) / len(scores))A loop can also build a new list from an old one, keeping only the items you want:
nums = [3, 8, 1, 6]
big = []
for n in nums:
if n > 4:
big.append(n)
print(big)To read many numbers from one line, .split() cuts the text into a list of strings. Turn each one into a number with int():
words = input("Numbers: ").split()
nums = []
for w in words:
nums.append(int(w))
print(nums, "add up to", sum(nums))How Python does it, and what it costs. The loop variable holds the item itself, not its index, so you rarely need range(len(...)). Each lap handles one item, so a loop over n items does n laps, and so do sum(), min() and max(): each walks the whole list once. Filtering into a new list is also one pass, which is much cheaper than removing items from the old list one by one.
Mistakes and edge cases.
- An empty list.
sum([])is 0, butmax([])givesValueError: max() iterable argument is empty, and an average divides bylen([]), which is 0. - Forgetting int() after split().
sum(["4", "7"])givesTypeError: unsupported operand type(s) for +: 'int' and 'str'. - Changing the list you're looping over. Removing items inside the loop skips some. Build a new list instead.
- Expecting an index. In
for x in [10, 20]:, x is 10 and then 20, not 0 and 1.
Quiz
What does this print?
for x in [2, 4, 6]: print(x // 2)What does this print?
print(sum([1, 2, 3]), max([4, 9, 2]))What does this print?
nums = [5, 12, 7, 20] count = 0 for n in nums: if n > 10: count += 1 print(count)What does
"3 7 1".split()give?- ['3', '7', '1'], a list of strings
- [3, 7, 1], a list of numbers
- 371
Which line has a mistake?
nums = [4, 6, 8] print(sum(nums) / len(num))
Coding tasks
Here are some prices:
prices = [12, 5, 8, 20]. Print the total of all the prices, then the most expensive price.Ask for whole numbers on one line, separated by spaces. Print how many of them are even.
Ask for whole numbers on one line, separated by spaces. Print a list of running totals: each item is the sum of all the numbers up to that point. For
1 2 3 4the answer is[1, 3, 6, 10].