sorted() is Python’s built-in function for creating a new sorted list from any iterable — with support for custom sorting via key, reverse order via reverse=True, and stable sorting. Unlike list.sort() (in-place), sorted() returns a new list, making it safer and more functional. In 2026, sorted() remains essential in data science (ranking pandas/Polars/Dask results, sorting time series), software engineering (priority queues, leaderboard generation), and algorithms (top-k, custom collation) — efficient O(n log n), stable, and works with any comparable elements or key functions.
Here’s a complete, practical guide to using sorted() in Python: basic sorting, key functions, reverse, real-world patterns (earthquake ranking, top-k events, custom collation), and modern best practices with type hints, performance, stability, and integration with NumPy/Dask/Polars/pandas/xarray.
Basic sorted(iterable, key=None, reverse=False) — returns new sorted list.
# Simple numeric sort
print(sorted([3, 1, 4, 1, 5, 9, 2, 6, 5]))
# [1, 1, 2, 3, 4, 5, 5, 6, 9]
# String sort (lexicographic)
print(sorted(['banana', 'apple', 'cherry', 'date']))
# ['apple', 'banana', 'cherry', 'date']
# Reverse sort
print(sorted([10, 5, 8, 3, 1], reverse=True))
# [10, 8, 5, 3, 1]
# Empty iterable
print(sorted([])) # []
key function — custom sorting criteria (like min()/max()).
events = [
{'mag': 7.2, 'place': 'Japan'},
{'mag': 8.1, 'place': 'Alaska'},
{'mag': 6.8, 'place': 'Chile'}
]
# Sort by magnitude (ascending)
sorted_events = sorted(events, key=lambda e: e['mag'])
print([e['place'] for e in sorted_events]) # ['Chile', 'Japan', 'Alaska']
# Sort by place name length (descending)
sorted_by_name_len = sorted(events, key=lambda e: len(e['place']), reverse=True)
print([e['place'] for e in sorted_by_name_len]) # ['Alaska', 'Japan', 'Chile']
# Multiple keys (stable sort)
sorted_multi = sorted(events, key=lambda e: (e['mag'], len(e['place'])))
print([e['place'] for e in sorted_multi]) # ['Chile', 'Japan', 'Alaska']
Real-world pattern: earthquake ranking & top-k strongest events — using sorted with key.
import pandas as pd
df = pd.read_csv('earthquakes.csv')
# Pandas: top 10 strongest events
top_10 = df.sort_values('mag', ascending=False).head(10)
print(top_10[['mag', 'place', 'time']])
# Pure Python: top 5 by magnitude (list of dicts)
quakes = df.to_dict('records')
top_5 = sorted(quakes, key=lambda e: e['mag'], reverse=True)[:5]
for q in top_5:
print(f"Mag {q['mag']:.1f} - {q['place']} ({q['time']})")
# Polars: sorted lazy
import polars as pl
pl_df = pl.from_pandas(df)
top_pl = pl_df.sort('mag', descending=True).head(10)
print(top_pl)
# Dask: lazy sort (computes on demand)
import dask.dataframe as dd
ddf = dd.from_pandas(df, npartitions=4)
top_dask = ddf.nlargest(10, 'mag').compute()
print(top_dask)
Best practices for sorted() in Python & data workflows. Prefer sorted(iterable, key=func, reverse=True) — for new sorted list; use .sort() only for in-place. Modern tip: use Polars df.sort('mag', descending=True) — fast columnar sort; Dask ddf.nlargest(n, 'col') for top-k. Use key=operator.itemgetter('mag') — faster than lambda. Use key=lambda x: (-x['mag'], x['time']) — multi-key descending. Add type hints — def rank_events(events: list[dict]) -> list[dict]: return sorted(events, key=lambda e: e['mag'], reverse=True). Use sorted() with enumerate() — sorted(enumerate(lst), key=lambda x: x[1]) for index of max/min. Use sorted() with zip() — sorted(zip(scores, names), reverse=True) for ranked names. Use sorted() in comprehensions — [x for _, x in sorted((f(item), item) for item in seq)]. Use sorted(set(seq)) — unique sorted list. Use sorted(df['col'].unique()) — sorted unique values. Use sorted() with key=str.lower — case-insensitive string sort. Use sorted() with key=len — sort by length. Use sorted() with key=abs — sort by absolute value. Use sorted(range(n), key=lambda i: df.iloc[i]['mag']) — sort indices by column value. Use sorted() in assertions — assert sorted(lst) == expected. Use sorted() in tests — verify order. Use sorted() with reversed() — list(reversed(sorted(seq))) for descending. Use sorted() with stability — preserves order of equal elements. Use sorted() with operator.attrgetter('mag') — for objects. Use sorted() with operator.itemgetter(1) — for tuples/lists. Use sorted() with locale.strxfrm — locale-aware string sort. Profile performance — sorted() is O(n log n); use partial sort for top-k (heapq.nlargest).
sorted(iterable, key=None, reverse=False) returns a new sorted list — stable, customizable via key, supports reverse order. In 2026, use for ranking, ordering results, custom collation, and integrate with pandas/Polars/Dask for sorted views and top-k extraction. Master sorted(), and you’ll create ordered sequences efficiently and expressively in any Python workflow.
Next time you need a sorted version of something — use sorted(). It’s Python’s cleanest way to say: “Give me the items in order — with any custom sorting rule I want.”