Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is enumerate()?


What you need to know

Python
models = ["model-a", "model-b", "model-c"]for i, name in enumerate(models):    print(i, name)# 0 model-a# 1 model-b# 2 model-cprint(list(enumerate(models, start=1)))# [(1, 'model-a'), (2, 'model-b'), (3, 'model-c')]print(enumerate(models))      # <enumerate object at 0x...>

What it returns

enumerate returns an iterator — an object that produces pairs only when asked. It does not build a list of pairs in memory, so enumerating a 10 GB file costs no extra memory. Wrap it in list() only when you really need all the pairs at once.

Each pair is a tuple, and for i, name in ... unpacks it into two variables.

Why not range(len(...))?

  • It works only on sequences with len() and indexing. Files, generators and sets have neither.
  • items[i] repeats the lookup and invites off-by-one mistakes.
  • A hand-made counter (i = 0 ... i += 1) is easy to forget, especially when a continue skips the increment.

Combining with zip

zip(a, b) pairs items from two iterables. When you also need the index, nest them:

Python
preds  = ["refund", "kyc", "other"]labels = ["refund", "kyc", "refund"]for i, (p, y) in enumerate(zip(preds, labels)):    if p != y:        print(f"row {i}: predicted {p}, expected {y}")# row 2: predicted other, expected refund

A real-life example

Before loading a transactions CSV into a fraud model, you validate every row and report line numbers the finance team can find in Excel. The header is line 1, so data rows start at line 2:

Python
import csv, iodata = io.StringIO(    "txn_id,amount,currency\n"    "T1,499.00,INR\n"    "T2,,INR\n"    "T3,120.50,USD\n"    "T4,abc,INR\n")bad = []for line_no, row in enumerate(csv.DictReader(data), start=2):    try:        float(row["amount"])    except ValueError:        bad.append(line_no)print("bad amounts on lines:", bad)      # bad amounts on lines: [3, 5]

csv.DictReader is an iterator over the file, so range(len(...)) is not even possible without loading everything first. enumerate(..., start=2) gives the exact spreadsheet line numbers, and the file is still read one line at a time.

Follow-up questions to expect

  • "What does enumerate return?" — A lazy iterator of (index, item) tuples.
  • "How is it different from zip?" — enumerate pairs each item with a counter; zip pairs items from two or more iterables. zip(range(len(x)), x) is a clumsy enumerate.
  • "Can you enumerate a dictionary?" — Yes. enumerate(d) gives indexes and keys; enumerate(d.items()) gives indexes and (key, value) pairs.