Course curriculum
Python · LESSON 4 OF 5

Repeat work with loops and lists

Visit list items, understand range boundaries and accumulate a result without repeated code.

About 10 minutes · Beginner

Visit 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.

Python
subjects = ["Maths", "Physics", "Computing"]
for number, subject in enumerate(subjects, start=1):
    print(f"{number}. {subject}")
Expected output
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.

Python
marks = [60, 75, 81]
total = 0
for mark in marks:
    total += mark
print(total)
Expected output
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.

Python
for attempt in range(1, 4):
    print(attempt)
Expected output
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
Python
passed = 0
for mark in [35, 62, 40, 28]:
    if mark >= 40:
        passed += 1
print(passed)  # 2

Keep exploring: official Python documentation.

0 of 5 completed on this device