Learning Goals
3 minBy the end of this lesson you can:
- Use
for item in listto walk every value in a list without writing a single index. - Use
enumerate(list, start=1)when you need each item and its position. - Build a running total or running count by iterating a list of numbers.
Warm-Up
5 minLast lesson we learned a list holds many items in order; my_list[0] is the first, my_list[-1] the last, and len() counts them. Today we add the cleanest way to look at every item in turn.
Quick predict-the-output puzzle. What does Python print?
drinks = ["teh tarik", "kopi-O", "milo ais"] for drink in drinks: print(drink)
Show the answer
teh tarik kopi-O milo ais
No [0], no range(len(...)) — just "for each drink in drinks, print the drink". That's the whole pattern.
New Concept · Walk the Chest
12 minThe hand-me-each-item analogy
Imagine handing a friend the items from a treasure chest, one at a time. You don't shout out box numbers — you just pass the next item over. That's what for item in list does: Python pulls each item out, gives it a temporary name, and runs your loop body.
Old way vs new way
Last lesson's stretch task used an index counter:
# old way — using indices dishes = ["nasi lemak", "roti canai", "satay"] for i in range(len(dishes)): print(dishes[i])
Two things to track: i, and what dishes[i] means. Easy to mistype, easy to off-by-one. The new way drops both worries:
# new way — direct iteration dishes = ["nasi lemak", "roti canai", "satay"] for dish in dishes: print(dish)
The variable dish is brand new — it didn't exist before the loop. Python invents it, fills it with the next item each pass, and you use it however you like.
When you do want the position — enumerate
Sometimes you need both the item and its number. enumerate() wraps your list and hands back pairs.
dishes = ["nasi lemak", "roti canai", "satay"] for i, dish in enumerate(dishes, start=1): print(i, ".", dish) # → 1 . nasi lemak # → 2 . roti canai # → 3 . satay
start=1 tells enumerate to count humans-style from 1, not from 0. Drop it and it counts from 0 like every other list index.
Reach for for item in list by default. Use enumerate only when you actually need the position. Use for i in range(len(...)) almost never — it's a code smell in real Python.
Worked Example · Pei Shan's Hawker Total
12 minThe job
Pei Shan's stall at Pasar Pagi Taman Connaught has four orders in tonight. We have a list of prices in ringgit. We want to add them up and print the total — without typing each price into a giant + chain.
The pattern · running total
Save as hawker_total.py:
Code
# hawker_total.py — total of tonight's orders prices = [5.50, 3.00, 8.00, 2.50] total = 0 for price in prices: total = total + price print("Total: RM", total)
Output
Total: RM 19.0
Read the loop aloud: "For each price in prices, add it to total." The trick is the total = 0 before the loop — that's the empty bowl we're filling. Forget that line and Python crashes with NameError: name 'total' is not defined.
Running totals power score-keepers, shopping-cart bills, leaderboards, calorie counters — anywhere you sweep a list and squeeze it down to one number.
Try It Yourself
13 minTwo tasks today (plus an optional stretch). Type each, run it, and only peek at the hint if you're truly stuck.
Create a list of five drinks from your favourite mamak. Use for drink in drinks to print each on its own line — no range, no [i].
Hint
drinks = ["teh tarik", "kopi-O", "milo ais", "sirap bandung", "limau ais"] for drink in drinks: print(drink)
Your five drinks can be different — the shape of the loop is what matters.
Given a list of four prices, count how many are above RM 3.00 using a for loop and an if. Print the count.
Hint
prices = [3.00, 2.50, 4.00, 3.50] count = 0 for p in prices: if p > 3.00: count = count + 1 print("Over RM 3:", count)
Same shape as the worked example — but instead of adding a price to total, you add 1 to count only when the price is above the cutoff.
Print the same five drinks from task 1, but with a position number — 1. teh tarik, 2. kopi-O, and so on. Use enumerate.
Hint
drinks = ["teh tarik", "kopi-O", "milo ais", "sirap bandung", "limau ais"] for i, drink in enumerate(drinks, start=1): print(i, ".", drink)
enumerate(drinks, start=1) gives you pairs like (1, "teh tarik"), (2, "kopi-O")… The for i, drink in … bit unpacks each pair into two variables in one go.
Mini-Challenge · Wei Jie's Cheapest Nasi Lemak
8 minWei Jie is hunting for the cheapest nasi lemak at the Sunday food court. He's collected prices from five stalls. Write a script cheapest.py that prints the lowest price in the list.
- Start with this list:
prices = [5.50, 4.00, 7.00, 3.50, 6.00]. - Use
for price in pricesto walk every value. - Keep a variable
cheapestthat holds the smallest price seen so far. Start it atprices[0]. - Print the final answer like:
Cheapest: RM 3.5.
Stretch. Print the stall number too (1 to 5) using enumerate.
Show one possible solution
# cheapest.py — find the cheapest nasi lemak prices = [5.50, 4.00, 7.00, 3.50, 6.00] cheapest = prices[0] for price in prices: if price < cheapest: cheapest = price print("Cheapest: RM", cheapest)
The non-negotiables are: starting cheapest from a real price (not 0!), the for price in prices loop, and the inner if price < cheapest check. Starting at 0 would never get beaten and the answer would always be wrong.
Recap
3 minfor item in list is the cleanest way to walk a collection. Pair it with a counter or running total before the loop and you can answer almost any "how many" or "how much" question. Reach for enumerate only when the position itself matters.
Vocabulary Card
for item in list- The standard Python pattern for visiting every item in a list. The loop variable is named on the fly.
- enumerate(list, start=1)
- Wraps a list to give back position + item pairs.
start=1counts from one; default counts from zero. - running total
- A variable defined before a loop, added to inside the loop. Squeezes a list down to one number.
Homework
4 minCreate a new file snack_bill.py — a personalised snack-bill calculator.
- Build a list called
snackswith the names of five snacks you'd order at the kantin (e.g."kuih","keropok","roti bakar"). - Build a second list called
priceswith the matching price for each snack, in the same order. - Use
for price in pricesto compute the total bill and print it asTotal: RM <total>. - Use
enumerate(snacks, start=1)to print a numbered list of the snacks beneath the total.
Bring snack_bill.py next class — we'll add list methods like append, pop and sort in PY-L1-17.
Sample · snack_bill.py
# snack_bill.py — kantin snack bill snacks = ["kuih", "keropok", "roti bakar", "kaya toast", "pisang goreng"] prices = [1.50, 1.00, 2.50, 3.00, 2.00] total = 0 for price in prices: total = total + price print("Total: RM", total) for i, snack in enumerate(snacks, start=1): print(i, ".", snack)
Your snacks and prices can be different — five of each, same order. The non-negotiables are: total = 0 before the loop, a for price in prices running total, and an enumerate walk for the numbered list. Don't fret over decimal formatting — that's f-strings in Level 2.