enumerate() and Unpacking – Powerful Pattern for Data Science 2026
Combining enumerate() with unpacking is a very Pythonic and frequently used pattern in data science. It allows you to iterate over a sequence while having access to both the index (or rank) and the value at the same time, making your code cleaner and more expressive.
TL;DR — The Power Pattern
for idx, value in enumerate(data):— Basic formfor rank, item in enumerate(data, start=1):— 1-based ranking- Works beautifully with lists, tuples, DataFrame rows, and more
1. Basic enumerate() + Unpacking
scores = [87, 95, 76, 92, 88]
for rank, score in enumerate(scores, start=1):
print(f"Rank {rank}: {score} points")
2. Real-World Data Science Examples
import pandas as pd
df = pd.read_csv("sales_data.csv")
# Example 1: Numbered output of top sales
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']:8} | Customer {row['customer_id']}")
# Example 2: Feature ranking with importance scores
feature_importance = {
"amount": 0.42,
"quantity": 0.31,
"region": 0.18,
"category": 0.09
}
for rank, (feature, importance) in enumerate(
sorted(feature_importance.items(), key=lambda x: x[1], reverse=True),
start=1
):
print(f"#{rank} {feature:12} : {importance:.4f}")
3. Advanced Pattern with Multiple Unpackings
transactions = [
{"id": 1001, "amount": 1250.75, "region": "North"},
{"id": 1002, "amount": 890.50, "region": "South"},
{"id": 1003, "amount": 2340.00, "region": "East"}
]
for idx, (trans_id, amount, region) in enumerate(
[(t["id"], t["amount"], t["region"]) for t in transactions],
start=1
):
print(f"Transaction {idx:2d}: ID {trans_id} | ${amount:7.2f} | {region}")
4. Best Practices in 2026
- Use
enumerate(..., start=1)when creating rankings or numbered outputs - Combine with unpacking for clean, readable loops
- Use
enumerate()withitertuples()for better performance on large DataFrames - Keep the loop body reasonably simple for maintainability
- Use descriptive variable names for both the index and the value
Conclusion
The combination of enumerate() and unpacking is a powerful and very Pythonic pattern in data science. It eliminates the need for manual counters and makes your loops cleaner and more readable. In 2026, this pattern is commonly used when creating ranked lists, processing rows with their positions, or generating numbered reports from data.
Next steps:
- Look for loops in your code that use manual counters and refactor them using
enumerate()with unpacking