Enumerate Function
TL;DR
The enumerate()
function adds automatic counters to any iterable, returning tuples of (index, value) pairs that make loops cleaner and more Pythonic.
Interesting!
You can start counting from any number using the start
parameter, making enumerate perfect for creating numbered lists that don’t begin at zero.
Basic Enumeration
The simplest use case pairs each item with its index:
python code snippet start
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
python code snippet end
Custom Starting Numbers
The start
parameter lets you begin counting from any number:
python code snippet start
# Create a numbered alphabet starting from 1
alphabet = [chr(x) for x in range(ord('a'), ord('z')+1)]
for num, letter in enumerate(alphabet, start=1):
print(f"{num}: {letter}")
# Output: (1, 'a'), (2, 'b'), (3, 'c')... (26, 'z')
python code snippet end
List Comprehensions with Enumerate
Enumerate works beautifully in list comprehensions and generator expressions:
python code snippet start
# Create position-value pairs
data = ['red', 'green', 'blue']
indexed = [(i, color) for i, color in enumerate(data)]
# Result: [(0, 'red'), (1, 'green'), (2, 'blue')]
python code snippet end
Why Use Enumerate
Instead of manually tracking indices with range(len())
, enumerate provides a cleaner, more readable solution that’s less error-prone and more expressive about your intent.
Built-in Functions Control Flow Tools
Reference: enumerate() - Python Documentation