Python for Loop: Repeat Code for Each Item
What Is a for Loop?
A for loop runs the same lines of code once for every item in a list. You write the lines once, and Python repeats them for you.
Say you want to greet three friends. Without a loop, you write one print() per friend:
print("Hello, Sunny!")
print("Hello, Rocky!")
print("Hello, Lucky!")Hello, Sunny! Hello, Rocky! Hello, Lucky!
That works for three friends. But for 300? With a for loop and the list from chapter 9, two lines do it all:
friends = ["Sunny", "Rocky", "Lucky"]
for friend in friends:
print("Hello,", friend + "!")Hello, Sunny! Hello, Rocky! Hello, Lucky!
Add a fourth name to the list and run it again. The loop greets everyone, and you didn't touch the print() line.
Think of it like a teacher calling the roll: the teacher goes down the list, one name at a time, and does the same thing for each name.
How it runs
- Python takes the first item from the list and puts it in
friend. - It runs the indented lines.
- Then it takes the next item and runs the lines again.
- When there are no items left, the loop ends and Python carries on below it.
Each run of the indented lines is called an iteration (a fancy word for "one time round").
- Start: Start
- Step: Take the next name from the list
- Input or output: Show: Hello, name!
- Decision: Any names left?yesGo back up and take the next namenoLeave the loop
- End: End
The "go back up" is what makes it a loop: the same two boxes run again and again, once per name.
A for loop repeats its indented lines once for every item in a list.