Lesson explanation
After this lesson, you will be able to:
range() for numeric repetition and predict its exclusive stop value.enumerate() when both a number and a value are needed.Python for loops usually iterate over values directly:
for service in services:
print(service)This is often clearer than manually managing indexes. Use range() when the problem is genuinely about numbers, positions, or a fixed number of repetitions.
range(start, stop) includes start but stops before stop. A third argument sets the step:
range(2, 9, 2)produces 2, 4, 6, and 8.
When you need a display number and the value together, enumerate(values, start=1) is usually clearer than range(len(values)).
Loops also commonly update totals or counters. Initialize the accumulator before the loop, update it inside the block, and use the final result after the loop.
The provided sequence values in this lesson are inputs for loop practice. Full list operations are covered in the data-structures unit.
💡 Tip: Start with
for item in items. Reach for numeric indexes only when the index itself has meaning.
Loop variables receive each value one at a time.
regions = ["us", "eu", "apac"]
for region in regions:
print(f"Region: {region}")Output:
Region: us
Region: eu
Region: apacNo index is needed because the task is about the region values.
The stop value is not included.
for attempt in range(1, 4):
print(f"Attempt {attempt}")Output:
Attempt 1
Attempt 2
Attempt 3The loop stops before 4.
The third argument controls the distance between generated values.
for port in range(9000, 9005, 2):
print(port)Output:
9000
9002
9004The sequence advances by two each time.
enumerate()enumerate() gives you both a counter and the current value.
workers = ["api", "queue", "mailer"]
for number, worker in enumerate(workers, start=1):
print(f"{number}. {worker}")Output:
1. api
2. queue
3. mailerThe displayed numbering starts at one without manual index arithmetic.
Initialize the accumulator before the loop.
durations = [12, 18, 15]
total = 0
for duration in durations:
total += duration
print(f"Total: {total}")Output:
Total: 45Each iteration adds one duration to the running total.
range() to be included.Python for Developers
Assembled code
Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.
0 / 6 tasks completed
| Need | Preferred loop |
|---|
| Work with each value | for item in items |
| Repeat over numbers | for number in range(...) |
| Number each value | for number, item in enumerate(...) |
| Build a total | Initialize before the loop, update inside |