Iterating and Sorting Lists in Python for Data Science

Datatypes Mar 19, 2026

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_list for 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() returns None
  • Sorting mixed types: sorted([3, "a"]) raises TypeError in Python 3
  • Sorting numbers stored as strings: "10" sorts before "9"; convert with key=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() and zip() 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(), and sorted(key=...)

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices