Skip to content
IT Vizag
← Lists, Dicts & Data

Looping over lists

Lesson 2 of 9 · 1 min read

Totals, averages and finding the biggest value.

🎬 Video version coming soon — read it now

Lists and for loops are made for each other. The loop visits every item, one by one.

fruits = ["mango", "banana", "guava"]
for fruit in fruits:
    print(f"I like {fruit}")

Totals and averages by hand

sum() does this for you, but writing it yourself teaches the pattern you'll use everywhere:

expenses = [120, 450, 80, 1200, 300]
total = 0
for amount in expenses:
    total += amount
print(f"Total ₹{total}, average ₹{total / len(expenses):.0f}")

Finding the biggest

temps = [31, 34, 29, 36, 33]
hottest = temps[0]
for t in temps:
    if t > hottest:
        hottest = t
print(f"Hottest: {hottest}°C")

Start with the first item, then replace it whenever you find something bigger. This "keep the best so far" pattern works for anything: cheapest price, longest name, highest score.

Building a new list

prices = [100, 250, 400]
with_gst = []
for p in prices:
    with_gst.append(round(p * 1.18, 2))
print(with_gst)   # [118.0, 295.0, 472.0]

Filtering

marks = [78, 32, 65, 18, 88]
passed = []
for m in marks:
    if m >= 35:
        passed.append(m)
print(f"{len(passed)} of {len(marks)} passed")

When you need the position too

enumerate() gives you the index and the item together:

toppers = ["Anil", "Bhavana", "Chaitanya"]
for rank, name in enumerate(toppers, start=1):
    print(f"{rank}. {name}")
Tip: Don't add or remove items from a list while looping over it. Build a new list instead, as in the filtering example.

In one line

Loop over a list to total, find the best, transform or filter it, and use enumerate() when you need positions.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend