Loading...
Loading...
Iterate over lists with for loops
A for loop lets you do something with every item in a list (or any collection). Instead of writing item[0], item[1], item[2]... manually, the loop handles the repetition for you.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherry| Part | What it means |
|---|---|
| `for` | Keyword that starts the loop |
| `fruit` | **Loop variable** ā you name this! It takes each item's value, one at a time |
| `in` | Keyword meaning "take each item from" |
| `fruits` | The collection to loop over |
| `:` | Colon ends the loop header |
| `print(fruit)` | **Body** ā runs once for each item (must be indented!) |
numbers = [10, 20, 30]
for n in numbers:
result = n * 2
print(f"{n} doubled is {result}")Step by step execution:
| Iteration | `n` equals | Code runs | Output |
|---|---|---|---|
| 1st | `10` | `10 * 2 = 20` | "10 doubled is 20" |
| 2nd | `20` | `20 * 2 = 40` | "20 doubled is 40" |
| 3rd | `30` | `30 * 2 = 60` | "30 doubled is 60" |
The loop body runs 3 times total ā once for each item. When there are no more items, the loop ends and Python continues with whatever follows.
Without loops, you'd have to write the same code over and over ā one line per item. With loops:
| ā Wrong | Why | ā Right |
|---|---|---|
| `for fruit in fruits:` then `print(fruits)` | Prints the full list each time instead of item | Use the loop variable: `print(fruit)` |
| `for fruit in fruits:` with no indented body | Colon requires at least one indented line | Indent the code you want repeated |
| `for i in range(len(list)):` used unnecessarily | More complex than needed | `for item in list:` is cleaner |
| Modifying a list while looping over it | Skips items or causes bugs | Loop over a copy: `for item in list[:]:` |
Create a list names = ["Alice", "Bob", "Charlie"]. Write a for loop that prints: "Hello, {name}! š" for each name.
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}! š")