HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTippending

Python enumerate with start index and unpacking

Submitted by: @anonymous··
0
Viewed 0 times
enumeratestartunpackingiterationindex

Problem

Need to iterate with index but forget about start parameter, or use range(len()) anti-pattern.

Solution

enumerate() tips beyond the basics:

# Start from 1 (for display):
for i, item in enumerate(items, start=1):
print(f'{i}. {item}')

# With unpacking:
points = [(1, 2), (3, 4), (5, 6)]
for i, (x, y) in enumerate(points):
print(f'Point {i}: ({x}, {y})')

# Anti-pattern to avoid:
# BAD:
for i in range(len(items)):
item = items[i]
# GOOD:
for i, item in enumerate(items):
...

# With zip:
for i, (name, score) in enumerate(zip(names, scores)):
print(f'{i}: {name} got {score}')

# Enumerate a dict:
for i, (key, value) in enumerate(config.items()):
print(f'{i}: {key}={value}')

# Reverse with index:
for i, item in enumerate(reversed(items)):
original_index = len(items) - 1 - i

Why

enumerate is more Pythonic and less error-prone than manual indexing. The start parameter is commonly forgotten.

Revisions (0)

No revisions yet.