Tech With Galvan
Courses/Python Mastery/Control Flow

Looping Dicts and Lists Like a Pro

20 min • Beginner • Module 6

enumerate, items, and the patterns that make loops clean.

Looping Dicts and Lists Like a Pro

You can loop. Now loop like the code was written by someone who’s done it for years. These four patterns separate beginner loops from professional ones — and they appear in every single project in this course.

Pattern 1: enumerate — when you need the position

Beginners do this:

names = ["Aarav", "Diya", "Kabir"]

i = 0
for name in names:
    print(f"{i + 1}. {name}")
    i += 1              # manual counter... works, but clunky

Professionals do this:

for i, name in enumerate(names, start=1):
    print(f"{i + 0}. {name}")     # 1. Aarav ...

enumerate hands you index and value together. The start=1 parameter sets where counting begins (default 0). No counter variable, no +=, no bugs.

Pattern 2: .items() — the only way to loop a dict

Beginners try this:

student = {"name": "Aarav", "age": 16, "grade": "10th"}

for key in student:
    print(key, student[key])       # works, but double-lookup is clunky

The pro way:

for key, value in student.items():
    print(f"{key}: {value}")

Output:

name: Aarav
age: 16
grade: 10th

.items() yields each key-value pair as a pair — unpack both in the loop line. This is the standard dict loop in all of Python.

Pattern 3: zip — parallel lists

When two lists belong together (names and scores, questions and answers):

questions = ["Capital of India?", "2 + 2?", "Largest ocean?"]
answers = ["New Delhi", "4", "Pacific"]

for question, answer in zip(questions, answers):
    print(f"Q: {question}")
    print(f"A: {answer}\n")

zip stitches the lists together position-by-position. Three related lists? zip(a, b, c) — it takes as many as you give it.

Pattern 4: sorted — loop in order

scores = [("Diya", 95), ("Aarav", 92), ("Kabir", 78)]

for name, score in sorted(scores, key=lambda pair: pair[1], reverse=True):
    print(f"{name}: {score}")

Output:

Diya: 95
Aarav: 92
Kabir: 78

sorted() doesn’t just sort alphabetically — the key= parameter tells it what to sort by (here: the second item of each pair), and reverse=True flips the order. That lambda is a one-line throwaway function — Module 7 teaches it fully; absorb the pattern now.

Leaderboards, “top 5 products,” “recent first” — this one line is behind all of them.

The anti-patterns (what pros don’t do)

# ❌ range(len()) — the beginner signature
for i in range(len(names)):
    print(names[i])

# ✅ loop the list directly
for name in names:
    print(name)

range(len(...)) works, but it’s noise — Python loops over values, not over indexes. Reach for range(len()) only when you truly need to modify positions.

Choosing the right loop pattern

You need… Pattern
Just the values for item in items:
Position + value enumerate(items, start=1)
Dict key + value dict.items()
Two+ parallel lists zip(a, b)
Specific order sorted(..., key=...)

✅ Checkpoint

  1. Replace the manual counter with one line. (for i, name in enumerate(names, start=1):)
  2. What does .items() yield? (Key-value pairs, unpacked as two variables)
  3. Sort a list of (name, score) pairs by score, highest first? (sorted(pairs, key=lambda p: p[1], reverse=True))
  4. What’s wrong with for i in range(len(names)):? (Nothing functional — but it’s noise; loop values directly)

Next: 🧪 Practice — the legendary loop exercises: star patterns, multiplication tables, FizzBuzz.