Put repetition on autopilot.
Visit items, count with range, and stop doing repetitive work by hand.
01 The idea
A for loop visits the items of an iterable one at a time. A list, string, or range can supply those items. The loop variable is assigned each item in turn. Use enumerate() when you need both a position and a value.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
for step, task in enumerate(["design", "build", "test"], start=1):
print(f"{step}. {task}")
print(list(range(2, 8, 2)))1. design 2. build 3. test [2, 4, 6]
03 Under the hood
- 1
enumerate() pairs each task with a counter. start=1 makes the display human-friendly without changing list indexing.
- 2
range(2, 8, 2) produces values beginning at 2, stepping by 2, and stopping before 8.
- 3
Indent all instructions that should repeat. Put the summary after the loop, at the outer indentation level. A for loop over an empty iterable runs its body zero times.
04 Your turn, builder
Print the squares of 1 through 4, one per line.
Reveal one possible solution +
for number in range(1, 5):
print(number ** 2)05 Check your signal
What values does range(3) supply?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.