Master Python Sorting: From Simple Lists to Custom Key Functions
This article explains various Python sorting techniques—including the built‑in sorted() function, the in‑place list.sort() method, key‑based sorting for complex structures, multi‑criteria ordering, and custom comparison via functools.cmp_to_key—providing clear code examples for each approach.
Python offers several flexible ways to sort data, ranging from simple numeric lists to complex structures such as dictionaries and tuples. The article covers the built‑in sorted() function, the list .sort() method, key‑based sorting for complex types, multi‑criteria sorting, and custom comparison functions using functools.cmp_to_key.
Using sorted()
The sorted() function accepts any iterable and returns a new sorted list without modifying the original data.
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 5, 6, 9]
# Descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [9, 6, 5, 5, 2, 1]Using .sort() method
The list method .sort() sorts the list in place, altering the original list.
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 5, 6, 9]
# Descending order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 2, 1]Sorting complex data types
When sorting lists of dictionaries or tuples, the key parameter can extract a sortable value from each element.
people = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# Sort by age ascending
sorted_people_by_age = sorted(people, key=lambda person: person['age'])
print(sorted_people_by_age)
# Sort by name descending
sorted_people_by_name_desc = sorted(people, key=lambda person: person['name'], reverse=True)
print(sorted_people_by_name_desc)
students = [
('John', 'A', 15),
('Jane', 'B', 12),
('Dave', 'B', 10)
]
# Multi‑criteria: first by grade, then by age
sorted_students = sorted(students, key=lambda s: (s[1], s[2]))
print(sorted_students)Custom comparison function (Python 3)
Python 3 no longer supports the cmp argument directly, but you can achieve similar behavior with functools.cmp_to_key.
from functools import cmp_to_key
def compare_items(x, y):
return x - y # Simple numeric comparison
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers, key=cmp_to_key(compare_items))
print(sorted_numbers)Choose the method that best fits your specific sorting needs—whether you need a new list, in‑place modification, sorting by complex keys, or custom comparison logic—to write concise and efficient Python code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
