Intro to Computer Science / Unit 8: Lists and Data
8.3 Iterating Over Lists
Notes
A for loop can go through each item of a list directly.
scores = [70, 85, 90]
total = 0
for s in scores:
total += s
print(total / len(scores))
- The total is 245, so this prints
81.66666666666667. - To use the index, loop with
range(len(scores))and usescores[i]. - Example:
for i in range(len(scores)): print(i, scores[i])prints0 70,1 85,2 90on separate lines. - Do not add or remove items from a list while looping over it.
Practice
What does
for x in [2, 4, 6]: print(x + 1) print?Each item is increased by 1.
What does
count = 0; for n in [3, 8, 5, 10]: if n > 4: count += 1, then print(count), display?The values 8, 5 and 10 are greater than 4, so count is 3.
What does
for i in range(len(["a", "b", "c"])): print(i) print?The length is 3, so range(3) gives 0, 1, 2.
Ready for more? Take the Unit 8 test.