🐍 Python for kids · Class 6 · Lesson 11 of 18 · Free
Looping Through Lists – Visit Every Item
⏱ About 30 minutes · ▶ run real Python here — nothing to install · no sign-in
In this lesson you will
- Visit every item of a list with a for loop.
- Use range(len()) and enumerate() when you also need the index.
- Total, search, filter and change a list inside a loop.
Your teacher has the marks of the whole class in a list. She wants the total, the topper and everyone who scored above 80. One loop over the list can answer all three.
How do I loop through a list in Python?
Write for item in my_list:. Each round, item becomes the next value from the list.
The loop runs exactly once for every item. It stops by itself after the last one.
Pick a clear loop variable name. for city in cities reads better than for x in cities.
▶cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"]2for city in cities:3 print("Train to", city, "is on time.")4print("All", len(cities), "trains checked.")
No variables yet.
▌✏️ Change this code and run it yourself
Train to Delhi is on time. Train to Mumbai is on time. Train to Chennai is on time. Train to Kolkata is on time. All 4 trains checked.
How do I add up all the numbers in a list?
Start a total at 0 before the loop. Add each item to it inside the loop.
After the loop, divide by len() to get the average.
Python also has sum(), but writing the loop yourself shows how sum() really works.
The loop also lets you add rules. For example, you could skip absent students marked as -1.
▶marks = [72, 88, 95, 64, 81]2total = 03for m in marks:4 total = total + m5average = total / len(marks)6print("Total:", total)7print("Average:", average)
No variables yet.
▌✏️ Change this code and run it yourself
Total: 400 Average: 80.0
How do I find the highest value with a loop?
Imagine holding a "best so far" card. You start with the first mark on it.
Look at each mark in turn. If a mark is bigger than your card, write the new mark on the card.
We keep the topper's name too. Two lists in the same order let us match each name to its mark.
▶names = ["Asha", "Bilal", "Charu", "Dev"]2scores = [78, 92, 85, 92]3best = scores[0]4topper = names[0]5for i in range(len(scores)):6 if scores[i] > best:7 best = scores[i]8 topper = names[i]9print("Topper:", topper, "with", best)
No variables yet.
▌✏️ Change this code and run it yourself
Topper: Bilal with 92
💡 Dev also has 92, but > is strict, so the first 92 (Bilal) stays the topper. Try >= and see what changes.
When should I use range(len()) or enumerate()?
for item in list gives you values but not positions. Sometimes you need the position too.
You may want to number the items. Or you may need the same index in a second list.
range(len(list)) gives the indexes 0, 1, 2 and so on. Then list[i] is the item.
enumerate() is a neater way. It hands you the index and the item together. Add start=1 for human counting.
0 Water plants 1 Fold clothes 2 Feed the cat Task 1: Water plants Task 2: Fold clothes Task 3: Feed the cat
How do I make a new list from an old one?
This is called filtering. You start with an empty list and append only the items you want.
The if inside the loop decides which items pass the test.
The original list stays the same. You get a second, shorter list.
Weather offices do exactly this. They pick out the days above 38 degrees to warn about a heatwave.
Heatwave readings: [41, 38, 43] Number of hot days: 3
How do I change every item in a list with a loop?
for item in list cannot change the list. item is only a copy of each value.
To change items, loop over the indexes and assign to list[i].
Below, a shop gives 10 rupees off every price, but no price may go below 0.
The 8-rupee pencil would become -2, so the if sets it to 0 instead.
Sale prices: [40, 0, 110, 25] Type three words: chai samosa jalebi ['CHAI', 'SAMOSA', 'JALEBI']
💡 split() breaks a sentence into a list of words at the spaces. That is a quick way to make a list from input.
🤔 Predict the output
Think like Python: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
nums = [3, 6, 9]
for n in nums:
print(n * 2)Question 2. What does this print?
words = ["sun", "moon", "sky"]
for i, w in enumerate(words):
if i == 1:
print(w)Question 3. What does this print?
data = [4, -2, 7, -5, 1]
count = 0
for x in data:
if x < 0:
continue
count = count + x
print(count)🧩 Your challenge
Make a spelling-test report. The list words has 5 words and the list answers has what a student wrote. Loop with enumerate(start=1) to print each question number with "correct" or "wrong". At the end, print the score out of 5.
Q1: correct Q2: wrong (it is friend) Q3: correct Q4: wrong (it is science) Q5: correct Score: 3 out of 5
⚠️ Common mistakes (and how to fix them)
❌ Wrong
marks = [40, 50, 60]
for m in marks:
m = m + 5
print(marks)No error message – but the list is still [40, 50, 60]. No grace marks were added.
✅ Right
marks = [40, 50, 60]
for i in range(len(marks)):
marks[i] = marks[i] + 5
print(marks)m is only a copy of each value. To change the list, assign to marks[i] using the index.
❌ Wrong
pets = ["dog", "cat", "parrot"]
for i in range(len(pets) + 1):
print(pets[i])IndexError: list index out of range
✅ Right
pets = ["dog", "cat", "parrot"]
for i in range(len(pets)):
print(pets[i])range(len(pets)) already gives 0, 1 and 2. Adding 1 asks for index 3, which does not exist.
❌ Wrong
nums = [1, 2, 3]
total = 0
for n in nums:
total = 0
total = total + n
print(total)No error message – but it prints 3 instead of 6.
✅ Right
nums = [1, 2, 3]
total = 0
for n in nums:
total = total + n
print(total)total = 0 inside the loop resets the total every round. Set it to 0 once, before the loop.
📌 Remember
- for item in my_list: runs once for every item, in order.
- Start a total at 0 before the loop and add to it inside.
- Keep a "best so far" variable to find the highest or lowest value.
- Use range(len(list)) or enumerate() when you need the index.
- Filter by appending the items you want to a new empty list.
- To change items, assign to list[i]; the loop variable is only a copy.
Finished the quiz and the challenge?
Questions students ask
How do I loop through a list with the index in Python?
Use for i, item in enumerate(my_list):. You get the index and the item together. Add start=1 to count from 1.
Why does changing the loop variable not change my list?
The loop variable holds a copy of each value. Use the index, like my_list[i] = new_value, to change the list.
Is it better to write a loop or use sum() and max()?
In real programs, sum() and max() are shorter. Writing the loop yourself teaches how they work and lets you add extra rules.
Can I remove items from a list while looping over it?
It is risky, because items shift and some get skipped. Build a new list with only the items you want to keep.