Course curriculum
Repeat work with loops and lists
Visit list items, understand range boundaries and accumulate a result without repeated code.
About 10 minutes · BeginnerVisit each item
A list stores an ordered collection. A for loop gives its variable each value in turn, so the same block can process every item.
The loop variable receives a value, not an index. When you also need a position, enumerate provides both; start=1 gives human-friendly numbering.
subjects = ["Maths", "Physics", "Computing"]
for number, subject in enumerate(subjects, start=1):
print(f"{number}. {subject}")1. Maths 2. Physics 3. Computing
Accumulate a result
Initialize an accumulator before the loop. Update it once for each item. Resetting it inside the loop would discard earlier work.
Python also offers sum for this common operation. Learn the loop version to understand the process, then use the built-in when it expresses your intention clearly.
marks = [60, 75, 81]
total = 0
for mark in marks:
total += mark
print(total)216
Understand the stopping point
range(1, 4) generates 1, 2 and 3. The stop value is excluded. This makes range(3) useful for exactly three repetitions.
A while loop repeats while a condition remains true. Ensure something in its body can eventually make that condition false, or the loop may never stop.
for attempt in range(1, 4):
print(attempt)1 2 3
Try it yourself
Use a loop to count how many marks in [35, 62, 40, 28] are at least 40.
Show a possible solution
passed = 0
for mark in [35, 62, 40, 28]:
if mark >= 40:
passed += 1
print(passed) # 2Keep exploring: official Python documentation.