Understanding Python Sorting: sort() vs sorted(), Custom and Multi-level Sorting, and Timsort
This article explains Python's built‑in sorting functions, demonstrates when to use sort() versus sorted(), shows how to implement custom key functions and multi‑level sorting, and describes the efficient Timsort algorithm behind them.
Today we discuss one of the most frequently used features in Python—sorting.
We compare the two built‑in sorting functions list.sort() and sorted() , show their differences, and give examples.
1. sort() vs sorted(): which is the king of sorting?
Python provides two sorting methods:
list.sort() → “dominant” style, modifies the original list in place and returns None.
sorted() → “gentle” style, returns a new sorted list leaving the original unchanged.
Example:
<code>nums = [3, 1, 4, 2]
sorted_nums = sorted(nums) # [1, 2, 3, 4]; nums stays [3, 1, 4, 2]
nums.sort() # nums becomes [1, 2, 3, 4]
</code>When to choose:
Keep original data → use sorted() .
Do not need original data → use sort() (faster, less memory).
2. Advanced usage: custom sorting rules
You can tell Python how to sort by providing a key function.
📌 Sort by string length
<code>words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=lambda x: len(x)) # ['date', 'apple', 'banana', 'cherry']
</code>📌 Sort by a dictionary value
<code>users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 20},
]
sorted_users = sorted(users, key=lambda x: x["age"]) # Charlie → Alice → Bob
</code>3. Ultimate challenge: multi‑level sorting
Example: sort students by total score descending, then by Chinese score descending, then by student ID ascending.
<code>students = [
[1, 90, 80, 70], # [id, Chinese, Math, English]
[2, 85, 95, 80],
[3, 90, 80, 70],
[4, 80, 70, 90],
]
sorted_students = sorted(
students,
key=lambda x: (-(x[1] + x[2] + x[3]), -x[1], x[0])
)
# Result: id2 (total 260) → id1 (total 240, Chinese 90) → id3 (total 240, Chinese 90) → id4 (total 240, Chinese 80)
</code>4. Behind the scenes: Timsort algorithm
Python’s sorting is fast because it uses Timsort, a hybrid of merge sort and insertion sort.
Best case: O(n) when data is partially ordered.
Average case: O(n log n) , comparable to quicksort.
Stable sort: equal elements preserve their original order.
Suitable scenarios: small datasets benefit from insertion sort, large datasets from merge sort.
5. Summary
Feature
Code example
Use case
Basic sort
sorted(nums)Simple ascending sort
Descending sort
sorted(nums, reverse=True)From large to small
Custom sort
key=lambda x: len(x)Sort by string length, etc.
Multi‑level sort
key=lambda x: (-total, -chinese, id)Complex rule‑based sorting
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.