Iterating and Sorting Lists in Python for Data Science – Best Practices 2026
Iterating and sorting lists are two of the most common operations in data science — whether ranking features by importance, sorting customer records, ordering dates, or processing results. Mastering the right techniques will make your code cleaner, faster, and more Pythonic.
TL;DR — Recommended Approaches
- Use
for item in my_listfor simple iteration - Use
enumerate()when you need index + value - Use
sorted()to get a new sorted list - Use
my_list.sort()to sort in place
1. Iterating Over Lists
features = ["amount", "quantity", "profit", "region", "category"]
# Simple iteration
for feature in features:
print(feature)
# With index using enumerate (very common in data science)
for rank, feature in enumerate(features, start=1):
print(f"Rank {rank}: {feature}")
# With zip for parallel iteration
importance = [0.42, 0.31, 0.18, 0.09, 0.05]
for feature, score in zip(features, importance):
print(f"{feature:12} : {score:.4f}")
2. Sorting Lists
# 1. sorted() - returns a new sorted list (recommended)
sorted_features = sorted(features) # alphabetical
# 2. sort() - sorts in place (modifies original)
features.sort()
# Sorting with key (very useful in data science)
feature_importance = [("amount", 0.42), ("region", 0.09), ("profit", 0.31)]
sorted_by_importance = sorted(feature_importance, key=lambda x: x[1], reverse=True)
3. Real-World Data Science Examples
import pandas as pd
# Small inline sample so this example runs as-is.
# In a real project you would load it: df = pd.read_csv("sales_data.csv")
df = pd.DataFrame({
"customer_id": [101, 102, 103, 104, 105, 106],
"customer_name": ["Ana", "Ben", "Chen", "Dana", "Eli", "Fay"],
"order_date": ["2026-01-05", "2026-01-12", "2026-02-03",
"2026-02-18", "2026-03-01", "2026-03-09"],
"amount": [1250.75, 890.50, 2340.00, 1780.25, 2615.40, 450.00],
"quantity": [3, 2, 5, 4, 6, 1],
"profit": [312.69, 222.63, 585.00, 445.06, 653.85, 112.50],
"region": ["North", "South", "East", "North", "West", "South"],
"category": ["Electronics", "Books", "Electronics", "Home", "Home", "Books"],
"rating": [5, 4, None, 3, 5, 4],
})
# Example 1: Sort features by importance
importance_dict = {"amount": 0.42, "quantity": 0.05, "profit": 0.31, "region": 0.18}
sorted_features = sorted(importance_dict.keys(),
key=lambda f: importance_dict[f],
reverse=True)
# Example 2: Iterate over sorted results
for rank, feature in enumerate(sorted_features, start=1):
print(f"#{rank} {feature:12} importance: {importance_dict[feature]:.4f}")
# Example 3: Sort DataFrame rows and iterate
top_sales = df.nlargest(10, "amount")
for idx, row in enumerate(top_sales.itertuples(), start=1):
print(f"#{idx} Customer {row.customer_id}: ${row.amount:,.2f}")
4. Best Practices in 2026
- Use
sorted()when you want to keep the original list unchanged - Use
.sort()only when you no longer need the original order - Always use
key=parameter for custom sorting (importance, dates, etc.) - Combine
enumerate()with sorting for ranked outputs - For very large lists, consider NumPy or pandas sorting when possible
How Python Sorting Works
Both sorted() and list.sort() use the same algorithm (Timsort), and both are stable: items that compare equal keep their original relative order. Stability lets you sort by several fields in steps — sort by the secondary key first, then by the primary key.
The key function is called once per element, and its result is what gets compared. You can return a tuple to sort by several fields at once. operator.itemgetter and operator.attrgetter are readable alternatives to a lambda.
Worked Example: Multi-Key Sorting of Sales Records
from operator import itemgetter
sales = [
{"region": "North", "amount": 1250.75},
{"region": "South", "amount": 890.50},
{"region": "North", "amount": 2340.00},
{"region": "East", "amount": 890.50},
]
# Region A-Z, then amount high-to-low (negate the number)
by_region = sorted(sales, key=lambda r: (r["region"], -r["amount"]))
for r in by_region:
print(f'{r["region"]:6} {r["amount"]:>9,.2f}')
# Top 2 by amount using itemgetter
top2 = sorted(sales, key=itemgetter("amount"), reverse=True)[:2]
print([r["amount"] for r in top2]) # [2340.0, 1250.75]
# Case-insensitive sort of names
names = ["bob", "Alice", "carol"]
print(sorted(names, key=str.lower)) # ['Alice', 'bob', 'carol']
Negating a number in the key reverses only that field, which is the simplest way to mix ascending and descending order in a single sort.
Common Mistakes
- Writing
items = items.sort():sort()returnsNone - Sorting mixed types:
sorted([3, "a"])raisesTypeErrorin Python 3 - Sorting numbers stored as strings:
"10"sorts before"9"; convert withkey=int - Modifying a list while iterating over it: iterate over a copy or build a new list
Quick Summary
- Use
sorted()for a new list,sort()to change the list in place - Sort by several fields with a tuple key; Python's sort is stable
- Pair iteration with
enumerate()andzip()for clean, index-free loops
Conclusion
Iterating and sorting lists are essential skills in data science. In 2026, combine enumerate() for indexed iteration, zip() for parallel processing, and sorted() with a key function for powerful ranked outputs. These patterns will make your feature selection, result ranking, and data exploration code much cleaner and more efficient.
Next steps:
- Review your current code and improve list iteration/sorting sections using
enumerate(),zip(), andsorted(key=...)