Sign in

Intro to Computer Science / Unit 8: Lists and Data

8.3 Iterating Over Lists

3 practice questionsNot yet reviewed

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 use scores[i].
  • Example: for i in range(len(scores)): print(i, scores[i]) prints 0 70, 1 85, 2 90 on 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?
What does count = 0; for n in [3, 8, 5, 10]: if n > 4: count += 1, then print(count), display?
What does for i in range(len(["a", "b", "c"])): print(i) print?

Ready for more? Take the Unit 8 test.