Iterating and Sorting Lists are two of the most essential daily operations when working with data in Python. Iteration lets you process each element — apply transformations, filter, aggregate, or extract insights. Sorting organizes data for display, ranking, searching, or analysis. In 2026, these operations power everything from simple scripts to large-scale data pipelines in pandas, Polars, and Dask. Python offers elegant, efficient, and expressive ways to iterate (for loops, comprehensions, enumerate, zip) and sort (sorted(), .sort(), key functions, custom comparators) — often vectorized or parallelized in modern libraries.
Here’s a complete, practical guide to iterating and sorting lists in Python: core iteration patterns, sorting techniques, real-world patterns (earthquake ranking, time series processing, feature extraction), and modern best practices with type hints, performance, stability, and integration with pandas/Polars/Dask/NumPy.
1. Iterating over Lists — from basic to advanced
numbers = [10, 20, 30, 40, 50]
# Basic for loop
for num in numbers:
print(num) # 10 20 30 40 50
# With index using enumerate() — preferred
for i, num in enumerate(numbers):
print(f"Index {i}: {num}")
# With index starting from 1
for i, num in enumerate(numbers, start=1):
print(f"Position {i}: {num}")
# Zip multiple lists — parallel iteration
places = ["Japan", "Chile", "Alaska", "Peru", "Mexico"]
for mag, place in zip(numbers, places):
print(f"M{mag} at {place}")
# Reverse iteration
for num in reversed(numbers):
print(num) # 50 40 30 20 10
# Step iteration (every second element)
for num in numbers[::2]:
print(num) # 10 30 50
2. Sorting Lists — in-place vs new list, basic to custom
scores = [85, 92, 78, 95, 88, 92]
# New sorted list (preferred, safe)
sorted_scores = sorted(scores)
print(sorted_scores) # [78, 85, 88, 92, 92, 95]
# In-place sort (modifies original list)
scores.sort()
print(scores) # [78, 85, 88, 92, 92, 95]
# Descending order
sorted_desc = sorted(scores, reverse=True)
print(sorted_desc) # [95, 92, 92, 88, 85, 78]
# Custom key function — sort by name length
names = ["Alice", "Bob", "Charlie", "David"]
sorted_by_len = sorted(names, key=len)
print(sorted_by_len) # ['Bob', 'Alice', 'David', 'Charlie']
# Multiple keys (stable sort)
students = [
{"name": "Bob", "age": 20},
{"name": "Alice", "age": 22},
{"name": "Charlie", "age": 20},
]
sorted_students = sorted(students, key=lambda s: (s["age"], s["name"]))
print([s["name"] for s in sorted_students])
# ['Bob', 'Charlie', 'Alice']
Real-world pattern: earthquake data iteration & sorting — ranking, filtering, time series
import pandas as pd
df = pd.read_csv('earthquakes.csv')
# Iterate & filter strong events
strong_events = []
for _, row in df.iterrows():
if row['mag'] >= 7.0:
strong_events.append({
'mag': row['mag'],
'place': row['place'],
'time': row['time']
})
# Sort by magnitude descending
ranked_strong = sorted(strong_events, key=lambda e: e['mag'], reverse=True)
# Top 5 strongest
print("Top 5 strongest earthquakes:")
for i, event in enumerate(ranked_strong[:5], 1):
print(f"{i}. M{event['mag']:.1f} - {event['place']}")
# Polars: vectorized iteration & sorting
import polars as pl
pl_df = pl.from_pandas(df)
strong_pl = pl_df.filter(pl.col('mag') >= 7.0).sort('mag', descending=True)
print(strong_pl.head(5))
Best practices for iteration & sorting in Python (2026)
- Prefer enumerate() over range(len()) — cleaner, safer:
for i, val in enumerate(lst) - Use zip() for parallel iteration —
for a, b in zip(list1, list2) - Use list comprehensions — for filtering & transformation:
[x**2 for x in lst if x > 0] - Use sorted() for new list — safer than lst.sort() unless in-place is required
- Use key=operator.itemgetter('mag') — faster than lambda for dicts/objects
- Use reverse=True — for descending sort
- Use stable sort — sorted() preserves relative order of equal elements
- Avoid modifying list while iterating — collect indices or build new list
- Use Polars .sort() — fast columnar sort:
df.sort('mag', descending=True) - Use Dask nlargest/nsmallest — top-k in distributed data
- Use heapq.nlargest() — efficient top-k without full sort
- Use type hints —
List[int],Sequence[float] - Use sorted() with key=str.lower — case-insensitive string sort
- Use sorted() with key=abs — sort by absolute value
- Use sorted() with key=len — sort by length
- Use sorted() with custom cmp_to_key — for complex comparisons (from functools)
Iterating and sorting lists are daily tasks in Python — master for loops, enumerate, zip, comprehensions, sorted() + key, and vectorized operations in Polars/Dask/pandas. These patterns give you clean, efficient, readable, and scalable data processing power.
Next time you need to process or order a collection — reach for these tools. They’re Python’s cleanest ways to say: “Walk through every item — then put them in perfect order.”