Python Tutorial
Python Sort Lists
sort() orders the list in place. reverse() flips the current order. sorted() returns a new list.
sort() and reverse()
Alphanumeric, ascending by default. Case-sensitive: capitals come before lowercase.
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
thislist.sort(reverse=True)
print(thislist)Custom Key
Pass a function as key. Use str.lower to ignore case.
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key=str.lower)
print(thislist)
print(sorted([3, 1, 2]))📘 Real-World Deep Dive
Sorting is the operation people code from scratch. Knowing <code>list.sort</code>, <code>sorted</code>, <code>key=</code>, and <code>functools.cmp_to_key</code> turns "sort by revenue desc with tiebreaker" into 1 line.
Real-Life Scenario
Sort a list of orders by multiple keys (status > total > date) and keep the original list unfrozen for follow-on edits.
Real-Life Example
from dataclasses import dataclass
from datetime import date
@dataclass
class Order:
oid: int
total: float
status: str
placed: date
orders = [
Order(1, 120.0, "paid", date(2026, 8, 19)),
Order(2, 25.0, "draft", date(2026, 8, 21)),
Order(3, 120.0, "paid", date(2026, 8, 17)),
Order(4, 300.0, "refund", date(2026, 8, 22)),
Order(5, 300.0, "paid", date(2026, 8, 20)),
]
STATUS_ORDER = {"paid": 0, "draft": 1, "refund": 2}
ranked = sorted(
orders,
key=lambda o: (STATUS_ORDER[o.status], # primary
-o.total, # secondary: desc
o.placed), # tertiary: asc
)
for o in ranked:
print(o)Expected Output
Order(oid=5, total=300.0, status='paid', placed=datetime.date(2026, 8, 20))
Order(oid=1, total=120.0, status='paid', placed=datetime.date(2026, 8, 19))
Order(oid=3, total=120.0, status='paid', placed=datetime.date(2026, 8, 17))
Order(oid=2, total=25.0, status='draft', placed=datetime.date(2026, 8, 21))
Order(oid=4, total=300.0, status='refund', placed=datetime.date(2026, 8, 22))Common mistakes
list.sort()returnsNone— assigning the result is a common silent bug.- Tuple comparator keys: tuples compare element-by-element but Python types differ — don't mix
strandint. - Numeric "reversed" sort needs negation; only since Python 3 you can write
reverse=Trueinstead.
🚀 Performance & Best Practices
- Pre-compute keys once with
items.sort(key=lambda x: (rank[x.id], x.score))— the key fn runs fewer times. operator.attrgetter/itemgetterbeat lambdas in micro-benchmarks.- For huge lists, consider
numpy.argsort+ vectorized gather.
🧪 Try It Yourself
- Refactor
rankedto useattrgetteron a frozen dataclass. - Sort the same list by stringified date and benchmark both.
- Write a comparator that handles missing values (treat
Noneas "always last").