Using enumerate() in Python – Best Practices for Data Science 2026
The enumerate() function is one of the most useful built-in tools in Python for data science. It allows you to loop over an iterable while keeping track of the index (position) at the same time, making your code cleaner and more Pythonic.
TL;DR — Why Use enumerate()
- Replaces manual counter variables
- Provides both index and value in each iteration
- Supports custom starting index with
start= - Makes code more readable and less error-prone
1. Basic Usage
scores = [85, 92, 78, 95, 88, 76]
# Without enumerate (old style)
for i in range(len(scores)):
print(f"Rank {i+1}: {scores[i]}")
# With enumerate (modern, cleaner)
for rank, score in enumerate(scores, start=1):
print(f"Rank {rank}: {score}")
2. Real-World Data Science Examples
import pandas as pd
df = pd.read_csv("sales_data.csv")
# Example 1: Adding row numbers
for idx, row in enumerate(df.itertuples(), start=1):
if row.amount > 1000:
print(f"Row {idx}: High value sale by customer {row.customer_id}")
# Example 2: Processing features with their positions
features = ["amount", "quantity", "profit", "region", "category"]
for position, feature in enumerate(features, start=1):
print(f"Feature {position:2d}: {feature:12} (dtype: {df[feature].dtype})")
# Example 3: Creating a ranked list
top_sales = df.nlargest(10, "amount")
for rank, (_, row) in enumerate(top_sales.iterrows(), start=1):
print(f"#{rank:2d} | ${row['amount']:8.2f} | {row['region']}")
3. Best Practices in 2026
- Use
enumerate(sequence, start=1)when you need 1-based ranking - Prefer
enumerate()over manual counters likei = 0; i += 1 - Use it with
itertuples()for better performance on large DataFrames - Combine with unpacking:
for idx, value in enumerate(data) - Keep the loop body clean — don't make it too complex
Conclusion
enumerate() is a small but incredibly useful built-in function that eliminates the need for manual index counters. In data science, it is commonly used when processing rows, ranking results, iterating over feature lists, or creating numbered outputs. Using enumerate() makes your code more Pythonic, readable, and less prone to off-by-one errors.
Next steps:
- Search your codebase for loops that use manual counters and replace them with
enumerate()