for loop over a list
You could print every item in a list by hand — print(items[0]), print(items[1]), and so on. But that breaks the moment the list changes size. A for loop runs the same code once for every item, no matter how many there are.
The basic for loop
Output:
Read it out loud: "for each fruit in fruits, print the fruit." On each pass through the loop, the variable fruit holds the next item.
The loop variable
fruit is just a name you choose. Python assigns each item to it in turn:
- First pass:
fruitis"apple" - Second pass:
fruitis"banana" - Third pass:
fruitis"cherry"
Pick a name that describes one item. A list of scores loops with for score in scores:.
Indentation defines the loop body
Just like if, the indented block is what repeats. Anything not indented runs only once, after the loop finishes:
Output:
Looping works on any list
The same pattern works with numbers, or any list:
Key takeaways
- A
forloop runs its indented block once for every item in a list - The loop variable (
for item in items:) holds the current item on each pass - Choose a loop variable name that describes a single item
- Indentation marks the loop body — unindented code runs after the loop ends
No comments yet. Add the first comment to start the discussion.