Level 1
0 / 100 XP

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

Python
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Output:

Text
apple banana cherry

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: fruit is "apple"
  • Second pass: fruit is "banana"
  • Third pass: fruit is "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:

Python
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # runs once per item print("Done!") # runs once, after the loop

Output:

Text
apple banana cherry Done!

Looping works on any list

The same pattern works with numbers, or any list:

Python
scores = [88, 92, 75] for score in scores: print(score)

Key takeaways

  • A for loop 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