Glossary

Enumerate

enumerate is a built-in function that takes an iterable and returns an iterator of (index, element) tuples. It replaces the anti-pattern of using range(len(sequence)) to get indices while iterating. Instead of for i in range(len(items)): item = items[i], you write for i, item in enumerate(items): — which is shorter, more readable, and works with any iterable, not just sequences.

enumerate accepts an optional start parameter that changes the starting index: for i, item in enumerate(items, start=1): counts from 1 instead of 0. This is useful for numbering output lines, menu options, or other displays where 1-based indexing is conventional.

enumerate is one of Python's most commonly used built-in functions and a hallmark of Pythonic code. It produces items lazily (as a generator), so it is memory-efficient even for large iterables. It is often combined with tuple unpacking in the loop header, and its output can be passed to dict() to create a mapping from indices to values. Along with zip, enumerate is one of the first built-ins new Python programmers should learn.

Related terms: For Loop, Iterator, Range

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.