Repeating With for Loops
Do something for every item in a list
Imagine you have a list of names and want to greet each one. You could write a print for every name by hand — but that's tedious and breaks the moment the list changes. Instead, we use a for loop to do something for each item automatically.
Looping over a list
names = ["Sam", "Ada", "Leo"]
for person in names:
print("Hello,", person)Here's what happens, step by step:
- Python takes the first item from
namesand puts it inperson. - It runs the indented block (the
print). - Then it grabs the next item, and repeats — until the list runs out.
So the loop runs three times, once per name. The word person is just a name we chose for "the current item" — you could call it anything.
Notice the familiar pattern from if: a colon at the end of the for line, and the repeated code indented beneath it.
Counting with range
When you want to repeat a fixed number of times, use range:
for number in range(5):
print(number)That prints 0 1 2 3 4 — five numbers, starting at 0. Again, computers love counting from 0. range(5) gives five values: 0 up to (but not including) 5.
Tip: A loop variable like person or number takes a new value on each pass. You don't set it yourself — the loop fills it in for you each time around.
Your turn
Add a name to the list and run it — notice you didn't have to add any new print lines. That's the power of loops.
Press “Run code” to see the result.
Quick check
Q1 How many times does this loop run: for x in ["a", "b", "c"]: ?
Q2 What numbers does range(5) produce?
Want to save your progress? It's free.
Create a free account