1. Home
  2. Blog
  3. Software Development

Software Development

Python enumerate() Explained: 7 Examples, start=1 and Mistakes to Avoid

Python enumerate() adds a counter to any loop, so you get the index and the value together without range(len()). Here are 7 tested examples, the start=1 trick for human-friendly numbering, and the mistakes that trip people up.

8 min read
Python enumerate() explained with examples

Key takeaways

  • Python enumerate turns any iterable into pairs of (index, value): for i, x in enumerate(items).
  • Pass start=1 to count from 1. It changes only the number, never which item you get.
  • It returns a lazy iterator, so wrap it in list() to see the pairs, and you cannot call reversed() on it directly.
  • Never delete items from a list while enumerating it: in our test, removing even numbers from [2, 4, 6, 7] left [4, 7].

Many Python beginners write for i in range(len(items)) and then look up items[i]. It works, but it is noisy and easy to get wrong. Python enumerate() is the built-in, readable way to loop with a counter. Every output below was copied from a run on Python 3.13.6, so you can trust it matches what you will see.

Quick answer

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
1 apple
2 banana
3 cherry

That is the whole idea: enumerate() hands you the position and the item on each pass, and start=1 makes the numbering human-friendly. New to loops altogether? Our Python tutorial for beginners covers the basics first.

How enumerate() works

The signature is enumerate(iterable, start=0). It takes anything you can loop over, such as a list, tuple, string, file or generator, and produces tuples of a counter and the next item:

print(list(enumerate(fruits)))
print(list(enumerate(fruits, start=1)))
[(0, 'apple'), (1, 'banana'), (2, 'cherry')]
[(1, 'apple'), (2, 'banana'), (3, 'cherry')]

In a for loop, Python unpacks each tuple straight into two names, i and fruit. You can call them anything, but i, idx or n for the counter keeps code familiar to other readers.

The start parameter (start=1)

start sets the first number. It does not skip items: with start=1 you still get the first element, labelled 1 instead of 0. Any integer works, including 100 or a negative number, which is handy for continuing a numbering across pages:

page = 3
for n, row in enumerate(rows_on_page, start=(page - 1) * 20 + 1):
    print(n, row)          # page 3 starts at 41

Tip: keep start=0 when you will use the counter as a list index, and use start=1 only for display, such as line numbers or ranking. Mixing the two causes off-by-one bugs.

7 practical examples

1. Number the lines of a report

for i, (name, score) in enumerate([("Asha", 91), ("Ravi", 78)], 1):
    print(i, name, score)
1 Asha 91
2 Ravi 78

Note the nested unpacking: each item is itself a tuple, so you write (name, score) in brackets.

2. Find the line numbers of errors in a log

log = ["ok", "ERROR disk", "ok", "ERROR net"]
for i, line in enumerate(log, start=1):
    if line.startswith("ERROR"):
        print("line", i, line)
line 2 ERROR disk
line 4 ERROR net

The same pattern works on a real file: for i, line in enumerate(f, start=1) streams the file line by line without loading it all into memory. See our Python file handling guide for opening files safely.

3. Build a lookup of positions

print({w: i for i, w in enumerate(["red", "green", "blue"])})
{'red': 0, 'green': 1, 'blue': 2}

Dictionary and list comprehensions accept enumerate() like any loop. Our list comprehension guide shows more patterns.

4. Loop over characters of a string

print(list(enumerate("hi")))     # [(0, 'h'), (1, 'i')]

5. Combine with zip()

print([(i, a, b) for i, (a, b) in enumerate(zip("xy", [1, 2]))])
[(0, 'x', 1), (1, 'y', 2)]

zip() walks two lists in step and enumerate() adds the counter on top.

6. Change items in place by index

prices = [100, 250, 80]
for i, p in enumerate(prices):
    prices[i] = round(p * 1.18, 2)    # add 18% tax
print(prices)                          # [118.0, 295.0, 94.4]

Replacing values at the same index is safe. It is adding or removing items that causes trouble, as shown below.

7. Show progress in a long job

for n, job in enumerate(jobs, start=1):
    process(job)
    if n % 100 == 0:
        print(f"{n} jobs done")

enumerate() with dictionaries

Looping over a dictionary yields its keys, so enumerate() numbers the keys. Use .items() to get keys and values:

d = {"b": 2, "a": 1}
print(list(enumerate(d)))
print(list(enumerate(d.items())))
[(0, 'b'), (1, 'a')]
[(0, ('b', 2)), (1, ('a', 1))]

Write the loop as for i, (key, value) in enumerate(d.items()). Dictionaries keep insertion order, so the numbering follows the order you added keys. Our Python dictionary guide has more on iteration.

enumerate() is lazy

enumerate() returns an enumerate object, an iterator that produces pairs on demand:

e = enumerate(fruits)
print(type(e).__name__, next(e), next(e))
enumerate (0, 'apple') (1, 'banana')

Laziness is why it works on huge files and endless generators without using extra memory. It also means two limits: you can loop over the object only once, and reversed(enumerate(items)) raised TypeError: 'enumerate' object is not reversible in our run. To count backwards, convert first with reversed(list(enumerate(items))), which gave [(2, 30), (1, 20), (0, 10)].

Is enumerate() slower than range(len())?

We timed 2,000 passes over a 1,000-item list, taking the best of five runs:

Loop style Time
for i, x in enumerate(lst) 0.052 s
for i in range(len(lst)): x = lst[i] 0.044 s
Manual counter i += 1 0.044 s

The difference is a few microseconds per thousand items, far below anything your users will notice, and the loop body almost always costs more. Choose enumerate() for clarity; it also works on iterables that have no len(), such as files and generators, where range(len()) cannot.

3 mistakes to avoid

1. Removing items while enumerating

nums = [2, 4, 6, 7]
for i, x in enumerate(nums):
    if x % 2 == 0:
        nums.pop(i)
print(nums)            # [4, 7]  (4 survived!)

Popping shifts the remaining items left, so the loop skips the next one. Build a new list instead: [x for x in nums if x % 2] gave the correct [7].

2. Forgetting to unpack

for item in enumerate(items) gives you tuples, not values. Write for i, item in enumerate(items).

3. Using start to skip items

enumerate(items, start=1) still begins with items[0]. To skip the first item, slice it, as in enumerate(items[1:], start=1), or use itertools.islice for iterators; see our itertools guide.

Python enumerate cheat sheet

Goal Code
Index and value for i, x in enumerate(items)
Count from 1 enumerate(items, start=1)
Dict keys and values for i, (k, v) in enumerate(d.items())
File line numbers for n, line in enumerate(f, 1)
Two lists plus counter for i, (a, b) in enumerate(zip(x, y))
See all pairs list(enumerate(items))
Reverse order reversed(list(enumerate(items)))

How enumerate() works inside

The Python documentation describes enumerate() as roughly equivalent to this small generator:

def my_enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1

Reading it explains every behaviour in this guide. The counter is a plain integer that grows by one per item, so start only shifts the numbers. The function pulls one item at a time from the iterable, which is why it is lazy and works on files and endless streams. And because it simply yields pairs, it can be consumed only once, like any generator. The real built-in is written in C, so it is faster than this Python version, but the logic is the same. If generators are new to you, our Python generators guide walks through yield step by step.

enumerate() vs range(len()) vs zip(): which to use?

You need Use Why
Index and value enumerate(items) Clear, works on any iterable
Only the values for x in items No counter means less noise
Values from two lists zip(a, b) Walks both in step
Index, plus two lists enumerate(zip(a, b)) Combines both tools
Only indexes, such as stepping by 2 range(0, len(items), 2) When you jump around by position

A quick rule: if you write items[i] inside the loop, you probably want enumerate().

Final thoughts

Python enumerate() is one of those small built-ins that instantly makes code cleaner. Use it whenever you need a position as well as a value, pass start=1 for display numbering, remember that it is a one-shot lazy iterator, and never shrink a list while you enumerate it. Once it is a habit, range(len()) will look odd in your own code.

Frequently asked questions

What does enumerate() do in Python?

It wraps an iterable and returns pairs of a counter and each item, so a loop can use the index and the value together without range(len()).

How do I make enumerate start at 1?

Pass the start argument: enumerate(items, start=1) or enumerate(items, 1). The first item is still included; only its number changes to 1.

Can I use enumerate with a dictionary?

Yes. enumerate(d) numbers the keys. Use enumerate(d.items()) and unpack with for i, (key, value) in it to get both keys and values.

Is enumerate slower than range(len())?

Only negligibly. In our test the difference was a few milliseconds over two million iterations, and enumerate also works on files and generators that have no length.

Why does reversed() fail on an enumerate object?

enumerate returns a lazy iterator that does not support reversed(). Convert it to a list first with reversed(list(enumerate(items))).

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →