Courses/Python Mastery/Module 6: Control Flow
Module 6 · Lesson 420 minBeginner

Looping Dicts and Lists Like a Pro

Lesson goal
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:

code
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:

code
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:

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

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

The pro way:

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

Output:

code
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):

code
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

code
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:

code
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)

code
# ❌ 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 valuesfor item in items:
Position + valueenumerate(items, start=1)
Dict key + valuedict.items()
Two+ parallel listszip(a, b)
Specific ordersorted(..., key=...)

✅ Checkpoint

  • Replace the manual counter with one line. *(for i, name in enumerate(names, start=1):)*
  • What does .items() yield? *(Key-value pairs, unpacked as two variables)*
  • Sort a list of (name, score) pairs by score, highest first? *(sorted(pairs, key=lambda p: p[1], reverse=True))*
  • 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.