I. Overview of Python Sorting Mechanisms
Sorting is the process of rearranging data according to certain rules. It is a common operation in data processing, retrieval, statistics, and business analysis.
Python provides two main sorting methods:
sorted(): a built-in sorting function that returns a new list and does not modify the original iterable.list.sort(): a method of list objects that modifies the original list in place and does not return a sorting result.
Both support:
- Ascending and descending sorting.
- Custom sorting rules.
- Using
keyto specify the sorting criterion. - Using
reverseto control the sorting direction. - Stable sorting.
The most important difference is: sorted() works with any iterable, while sort() applies only to lists.
numbers = [5, 2, 8, 1, 9]
# sorted: generates a new list
result = sorted(numbers)
print(result) # [1, 2, 5, 8, 9]
print(numbers) # [5, 2, 8, 1, 9]
# sort: modifies the original list directly
numbers.sort()
print(numbers) # [1, 2, 5, 8, 9]
1. Core Differences Between the Two Sorting Methods
| Comparison Dimension | sorted() | list.sort() |
|---|---|---|
| Type | Built-in function | List method |
| Operates on | Any iterable | list |
| Return value | New list | None |
| Whether it modifies the original object | No | Modifies in place |
| Whether key is supported | Yes | Yes |
| Whether reverse is supported | Yes | Yes |
| Whether sorting is stable | Yes | Yes |
| Typical scenario | Preserve original data | Sort the list directly |
2. How to Choose
If you need to preserve the original data, use sorted().
If you have confirmed that the original list can be modified and you do not need to preserve the original order, use list.sort().
data = [8, 3, 6, 1]
# Preserve the original data
ascending = sorted(data)
# Modify in place
data.sort()
Both methods use the same core sorting mechanism; the main differences lie in their interfaces and how they manage results.
II. sorted(): Generating a New Sorted List
sorted() is a built-in Python function that can sort any iterable and returns a new list.
1. Basic Syntax
sorted(iterable, *, key=None, reverse=False)
Parameter description:
| Parameter | Meaning | Default value |
|---|---|---|
| iterable | Iterable | Required |
| key | Sorting key function | None |
| reverse | Whether to sort in reverse | False |
Where:
iterable: can be a list, tuple, string, set, dictionary, generator, etc.key: specifies the sorting basis used for each element during comparison.reverse: when set toTrue, uses descending order.
Note: key and reverse are keyword-only arguments and cannot be passed as ordinary positional arguments.
2. Sorting Numbers
numbers = [8, 3, 10, 1, 6]
result = sorted(numbers)
print(result)
Output:
[1, 3, 6, 8, 10]
By default, values are arranged in ascending order.
3. Sorting Strings
names = ["Charlie", "Alice", "Bob", "David"]
result = sorted(names)
print(result)
Output:
['Alice', 'Bob', 'Charlie', 'David']
By default, strings are compared lexicographically by Unicode code point order, not by meaning or pinyin order in natural language.
4. Sorting Tuples
students = [
("Alice", 90),
("Bob", 85),
("Charlie", 95)
]
result = sorted(students)
print(result)
Output:
[('Alice', 90), ('Bob', 85), ('Charlie', 95)]
Tuples use lexicographical comparison by default:
- First compare the first element.
- If the first elements are equal, compare the second element.
- Compare subsequent elements in order.
- When the first differing element is encountered, it determines the comparison result.
If all corresponding elements are equal, the shorter tuple comes first.
5. Sorting Other Iterables
sorted() can handle more than just lists.
Tuple:
numbers = (5, 2, 8, 1)
result = sorted(numbers)
print(result)
print(type(result))
Output:
[1, 2, 5, 8]
<class 'list'>
Set:
numbers = {5, 2, 8, 1}
result = sorted(numbers)
print(result)
Dictionary:
user = {
"Charlie": 30,
"Alice": 25,
"Bob": 28
}
result = sorted(user)
print(result)
Output:
['Alice', 'Bob', 'Charlie']
Note that when you use sorted() directly on a dictionary, it sorts the dictionary's keys, not the key-value pairs.
If you need to sort by dictionary values, you can use items() and key.
scores = {
"Alice": 90,
"Bob": 85,
"Charlie": 95
}
result = sorted(
scores.items(),
key=lambda item: item[1]
)
print(result)
Output:
[('Bob', 85), ('Alice', 90), ('Charlie', 95)]
III. list.sort(): In-place Sorting
sort() is a method provided by Python list objects for directly modifying the order of elements in the list.
1. Basic Syntax
list.sort(*, key=None, reverse=False)
The parameter meanings are the same as those of sorted():
key: Specifies the sorting criterion.reverse: Controls the sorting direction.
The difference is that sort() does not create a new sorted result list; instead, it directly modifies the original list.
2. Basic Usage
numbers = [8, 3, 10, 1, 6]
numbers.sort()
print(numbers)
Output:
[1, 3, 6, 8, 10]
3. Return Value of sort()
This is a very common pitfall.
sort() is an in-place modification method, and its return value is None.
Incorrect usage:
numbers = [5, 2, 8, 1]
result = numbers.sort()
print(result)
Output:
None
Correct usage:
numbers = [5, 2, 8, 1]
numbers.sort()
print(numbers)
If you need to assign the sorting result to another variable, use sorted():
numbers = [5, 2, 8, 1]
result = sorted(numbers)
4. Effects of In-place Modification
numbers = [5, 2, 8, 1]
other = numbers
numbers.sort()
print(numbers)
print(other)
Output:
[1, 2, 5, 8]
[1, 2, 5, 8]
Because other and numbers reference the same list object, sorting in place will affect code that accesses that list through other references.
If you want an independent sorted result, you can use:
other = sorted(numbers)
IV. Ascending and Descending Sorting
By default, sorted() and sort() sort in ascending order.
The reverse parameter lets you control the sort direction.
1. Ascending Sort
numbers = [5, 2, 8, 1, 9]
result = sorted(numbers)
print(result)
Output:
[1, 2, 5, 8, 9]
Ascending order can be understood as arranging from smallest to largest.
2. Descending Sort
numbers = [5, 2, 8, 1, 9]
result = sorted(numbers, reverse=True)
print(result)
Output:
[9, 8, 5, 2, 1]
The same applies with sort():
numbers = [5, 2, 8, 1, 9]
numbers.sort(reverse=True)
print(numbers)
3. The Difference Between reverse and reversed
You need to distinguish the following three concepts:
| Operation | Effect | Return Value | Modifies the Original Object |
|---|---|---|---|
sort(reverse=True) |
Descending sort | None | Yes |
sorted(data, reverse=True) |
Descending sort | New list | No |
reversed(data) |
Iterates the existing order in reverse | Reverse iterator | No |
For example:
numbers = [3, 1, 5, 2]
print(sorted(numbers, reverse=True))
print(list(reversed(numbers)))
Output:
[5, 3, 2, 1]
[2, 5, 1, 3]
The two results are different:
sorted(..., reverse=True)rearranges the elements according to the sorting rule.reversed()merely traverses the existing order from back to front.
If the original list is not sorted, reversing is not the same as sorting in descending order.
V. The key Parameter: Custom Sort Criteria
key is a very important parameter in Python's sorting mechanism.
It lets us specify a function that extracts the sort key for each element.
Basic form:
sorted(data, key=function)
During sorting, Python computes the corresponding key value for each element and compares them based on those key values.
1. Sorting by String Length
words = ["Python", "Go", "Java", "JavaScript"]
result = sorted(words, key=len)
print(result)
Output:
['Go', 'Java', 'Python', 'JavaScript']
Here:
key=len
means sorting by the length of each string.
2. Custom Sorting with lambda
students = [
("Alice", 90),
("Bob", 85),
("Charlie", 95)
]
result = sorted(
students,
key=lambda item: item[1]
)
print(result)
Output:
[
('Bob', 85),
('Alice', 90),
('Charlie', 95)
]
lambda item: item[1] means taking the second element of each tuple as the sort key.
3. Sorting by a Field in a Dictionary
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 22}
]
result = sorted(
users,
key=lambda user: user["age"]
)
for user in result:
print(user)
Output:
{'name': 'Charlie', 'age': 22}
{'name': 'Alice', 'age': 25}
{'name': 'Bob', 'age': 30}
4. Using operator.itemgetter()
Python's operator module provides itemgetter(), which makes it easy to extract a specified position or key from an element.
from operator import itemgetter
students = [
("Alice", 90),
("Bob", 85),
("Charlie", 95)
]
result = sorted(
students,
key=itemgetter(1)
)
print(result)
It is equivalent to the following:
result = sorted(
students,
key=lambda item: item[1]
)
For dictionaries:
from operator import itemgetter
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 22}
]
result = sorted(
users,
key=itemgetter("age")
)
5. Using operator.attrgetter()
If the data consists of objects, you can use attrgetter() to extract attributes.
from operator import attrgetter
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
students = [
Student("Alice", 90),
Student("Bob", 85),
Student("Charlie", 95)
]
result = sorted(
students,
key=attrgetter("score")
)
for student in result:
print(student.name, student.score)
6. The key function is computed only once
Python sorting uses a key extraction mechanism.
For a single sorting operation, the sorting system computes a key value once for each element, and then uses those results for comparison, rather than re-executing the key function on every comparison.
For example:
def get_score(student):
print("计算排序键:", student["name"])
return student["score"]
students = [
{"name": "Alice", "score": 90},
{"name": "Bob", "score": 85},
{"name": "Charlie", "score": 95}
]
result = sorted(students, key=get_score)
The sort key for each student is computed only once.
This makes the key approach generally more efficient than the cmp approach, which repeatedly compares elements, when complex field extraction or computation is required.
VI. Multi-field sorting
In real-world business scenarios, it is often necessary to sort by multiple fields.
For example, sorting student grades may need to satisfy:
- Total score from highest to lowest.
- When total scores are equal, age from youngest to oldest.
- When ages are equal, names in alphabetical order.
Python can use tuples as the key to implement multi-field sorting.
1. Using a tuple key
students = [
{"name": "Alice", "score": 90, "age": 20},
{"name": "Bob", "score": 90, "age": 18},
{"name": "Charlie", "score": 95, "age": 21},
{"name": "David", "score": 90, "age": 18}
]
result = sorted(
students,
key=lambda item: (
-item["score"],
item["age"],
item["name"]
)
)
for student in result:
print(student)
The sorting criteria here are:
(
-item["score"],
item["age"],
item["name"]
)
Explanation:
-score: the higher the score, the smaller the negative number, so it is sorted first.age: the younger the age, the earlier it is sorted.name: name is used as the final sorting criterion.
2. Using Multi-Pass Stable Sorting
If different fields need different sort directions, you can also use Python's stable sorting mechanism, starting with the lower-priority fields.
students = [
{"name": "Alice", "score": 90, "age": 20},
{"name": "Bob", "score": 90, "age": 18},
{"name": "Charlie", "score": 95, "age": 21},
{"name": "David", "score": 90, "age": 18}
]
students.sort(key=lambda item: item["name"])
students.sort(key=lambda item: item["age"])
students.sort(key=lambda item: item["score"], reverse=True)
for student in students:
print(student)
Execution order:
- First sort by name in ascending order.
- Then sort by age in ascending order.
- Finally sort by score in descending order.
Because sorting is stable, later sorts will not change the relative order of elements with the same key from earlier sorts.
Therefore, the final result is equivalent to:
sorted(
students,
key=lambda item: (
-item["score"],
item["age"],
item["name"]
)
)
Note that the multi-pass stable sorting approach requires starting from the lowest-priority field and sorting by the highest-priority field last.
3. Choosing a Multi-Field Sorting Method
| Method | Advantages | Notes |
|---|---|---|
| Tuple key | Concise, intuitive, and usually sorts only once | Different field directions require designing the sort key |
| Multi-pass stable sorting | Each field can independently be set to ascending or descending order | More sorting passes |
| Custom comparator | Can express complex pairwise comparison rules | More complex to implement and usually less efficient than a key |
For most multi-field sorting, prefer a tuple key or multi-pass stable sorting.
7. Stable Sorting Mechanism
Stable sorting is an important feature of Python sorting.
Stable sorting means:
When two elements have the same sorting key, their relative order remains unchanged after sorting.
For example:
students = [
("Alice", 90),
("Bob", 85),
("Charlie", 90),
("David", 85)
]
result = sorted(
students,
key=lambda item: item[1]
)
print(result)
Output:
[
('Bob', 85),
('David', 85),
('Alice', 90),
('Charlie', 90)
]
In the original data:
- Bob is before David, and the two have the same score.
- Alice is before Charlie, and the two have the same score.
After sorting, the relative order within these two groups remains unchanged.
1. Why Stable Sorting Matters
In business data processing, a single sort field may not fully express the business rules.
For example, an order list is sorted first by creation time, then by order amount.
If the amounts are the same and you want the orders to retain their original chronological order, stable sorting is required.
orders = [
{"id": "A001", "amount": 100, "time": 3},
{"id": "A002", "amount": 200, "time": 1},
{"id": "A003", "amount": 100, "time": 2},
{"id": "A004", "amount": 200, "time": 4}
]
orders.sort(key=lambda order: order["time"])
orders.sort(key=lambda order: order["amount"], reverse=True)
for order in orders:
print(order)
Result:
{'id': 'A002', 'amount': 200, 'time': 1}
{'id': 'A004', 'amount': 200, 'time': 4}
{'id': 'A003', 'amount': 100, 'time': 2}
{'id': 'A001', 'amount': 100, 'time': 3}
Orders with the same amount still remain in ascending time order.
2. Both sorted() and sort() Are Stable
Python officially guarantees that both sorting methods are stable.
Therefore, you can safely use stable sorting to build multi-level sorting rules without implementing stability yourself.
VIII. Timsort: Python's Sorting Algorithm
Python's sorting mechanism mainly uses Timsort.
Timsort is an adaptive stable sorting algorithm that combines ideas from merge sort and insertion sort. It can take advantage of existing ordered runs in the data to improve sorting efficiency.
It was originally designed by Tim Peters for Python.
1. Why Timsort Is Needed
Real-world data is not always completely random.
For example:
numbers = [1, 2, 3, 4, 5, 9, 8, 7, 6]
This set of data already contains an ascending run and a descending run.
If all elements are treated as completely unordered data every time, the existing order information may be wasted.
Timsort identifies naturally ordered runs (Run) in the data and uses these runs to complete the subsequent sorting.
2. What Is a Run
A Run is a contiguous ordered segment identified by the sorting algorithm.
For example:
[1, 2, 3, 4] [9, 8, 7] [5, 6]
Where:
[1, 2, 3, 4]is an ascending run.[9, 8, 7]is a descending run.[5, 6]is an ascending run.
Timsort can identify these runs and obtain the final sorted result through subsequent processing and merging.
3. Core Idea of Timsort
The main process of Timsort can be summarized as follows:
- Scan the data and identify natural ordered runs.
- Make necessary adjustments to shorter runs.
- Organize the runs.
- Merge the runs according to a certain strategy.
- Obtain the final sorted result.
Flowchart:
flowchart TD
A["Start sorting"] --> B["Scan input data"]
B --> C["Identify natural ordered runs"]
C --> D{"Is the run length appropriate?"}
D -->|No| E["Extend using binary insertion sort"]
D -->|Yes| F["Keep the current ordered run"]
E --> G["Maintain the stack of runs to merge"]
F --> G
G --> H{"Are merge conditions met?"}
H -->|Yes| I["Merge adjacent ordered runs"]
I --> G
H -->|No| J{"Is there unprocessed data left?"}
J -->|Yes| B
J -->|No| K["Merge remaining ordered runs"]
K --> L["Output sorted result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This is a simplified description of the core ideas of Timsort and does not represent all internal implementation steps of a specific version.
4. Characteristics of Timsort
Adaptivity
It can take advantage of existing ordered intervals in the input data.
Stability
Elements with the same sort key preserve their original relative order.
Excellent Practical Performance
For partially ordered data, it can often be more efficient than traditional general-purpose sorting algorithms.
Worst-Case Time Complexity
It is typically:
For data that is already sorted or nearly sorted, the best case can reach:
Actual performance depends on the data distribution, the cost of comparison operations, and the implementation version.
5. Space Complexity
Timsort is not a strictly in-place sorting algorithm.
The sorting process may require additional temporary storage space.
In CPython, list.sort() uses extra memory to complete some merge operations. sorted() also needs to create a new result list.
Therefore:
sort()usually avoids creating one full result list compared withsorted(), but that does not mean it uses no additional space at all.sorted()needs to create an additional list object and may require temporary space during sorting.
You cannot simply think of sort() as sorting with zero additional memory.
IX. Sorting Mechanism for Custom Objects
When a list stores custom objects, Python needs to know how to compare these objects.
There are two common ways:
- Use
keyto extract object attributes. - Implement comparison methods for the object.
1. Sorting Objects Using key
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
students = [
Student("Alice", 90),
Student("Bob", 85),
Student("Charlie", 95)
]
result = sorted(
students,
key=lambda student: student.score
)
for student in result:
print(student.name, student.score)
This is one of the most recommended approaches.
This is because the sorting rule is explicit, and there is no need to change the object's own comparison behavior.
2. Using lt to Implement Comparison
Python sorting needs to be able to compare elements.
For custom objects, you can implement __lt__():
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __lt__(self, other):
return self.score < other.score
students = [
Student("Alice", 90),
Student("Bob", 85),
Student("Charlie", 95)
]
students.sort()
for student in students:
print(student.name, student.score)
__lt__() represents the less-than comparison operation.
When the sorting algorithm needs to determine the ordering relationship between two objects, it can call the corresponding comparison method.
However, for scenarios that require only one sort rule, using key is usually simpler.
3. Using total_ordering
functools.total_ordering can help generate the other ordering comparison methods after some comparison methods have been implemented.
from functools import total_ordering
@total_ordering
class Student:
def __init__(self, score):
self.score = score
def __eq__(self, other):
if not isinstance(other, Student):
return NotImplemented
return self.score == other.score
def __lt__(self, other):
if not isinstance(other, Student):
return NotImplemented
return self.score < other.score
It can supply other common comparison operators, but that does not mean all complex sorting rules should be implemented through object comparison methods.
10. Comparison Functions and cmp_to_key
Python 2 used to support passing a comparison function through the cmp parameter.
Python 3's sorted() and list.sort() have removed this direct cmp parameter.