Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is enumerate()?
What you need to know
1models = ["model-a", "model-b", "model-c"]2for i, name in enumerate(models):3 print(i, name)4# 0 model-a5# 1 model-b6# 2 model-c78print(list(enumerate(models, start=1)))9# [(1, 'model-a'), (2, 'model-b'), (3, 'model-c')]10print(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 acontinueskips the increment.
Combining with zip
zip(a, b) pairs items from two iterables. When you also need the index, nest them:
1preds = ["refund", "kyc", "other"]2labels = ["refund", "kyc", "refund"]3for i, (p, y) in enumerate(zip(preds, labels)):4 if p != y:5 print(f"row {i}: predicted {p}, expected {y}")6# row 2: predicted other, expected refundA 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:
1import csv, io23data = io.StringIO(4 "txn_id,amount,currency\n"5 "T1,499.00,INR\n"6 "T2,,INR\n"7 "T3,120.50,USD\n"8 "T4,abc,INR\n"9)10bad = []11for line_no, row in enumerate(csv.DictReader(data), start=2):12 try:13 float(row["amount"])14 except ValueError:15 bad.append(line_no)16print("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
enumeratereturn?" — A lazy iterator of(index, item)tuples. - "How is it different from
zip?" —enumeratepairs each item with a counter;zippairs items from two or more iterables.zip(range(len(x)), x)is a clumsyenumerate. - "Can you enumerate a dictionary?" — Yes.
enumerate(d)gives indexes and keys;enumerate(d.items())gives indexes and(key, value)pairs.