Master Python’s sorted() Function: 10+ Real-World Examples & Advanced Tips
Explore the versatile sorted() built‑in in Python through over ten practical examples, covering basic list and string sorting, custom key functions, reverse ordering, composite criteria, and real‑world use cases like sorting dictionaries and word‑frequency analysis, empowering you to write cleaner, more efficient code.
Introduction
The sorted() function is a built‑in Python tool for ordering any iterable, returning a new list while leaving the original data unchanged. Its signature is sorted(iterable, *, key=None, reverse=False), where iterable is the data to sort, key defines a custom sorting key, and reverse toggles descending order.
Basic Usage – Simple Data Sorting
Example 1: Sorting a list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 6, 9]Example 2: Sorting a list of strings
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words)
print(sorted_words) # Output: ['apple', 'banana', 'cherry']Advanced Techniques – Custom key Functions
Example 3: Sort strings by length
fruits = ["apple", "banana", "cherry", "date"]
sorted_by_length = sorted(fruits, key=len)
print(sorted_by_length) # Output: ['date', 'apple', 'cherry', 'banana']Example 4: Sort numbers by absolute value
nums = [-5, -3, 2, 4, -1]
sorted_abs = sorted(nums, key=abs)
print(sorted_abs) # Output: [-1, 2, -3, 4, -5]Example 5: Sort full names by last name
people = ["Alice Johnson", "Bob Smith", "Charlie Brown"]
sorted_by_last_name = sorted(people, key=lambda name: name.split()[-1])
print(sorted_by_last_name) # Output: ['Charlie Brown', 'Alice Johnson', 'Bob Smith']Reverse Sorting – Using the reverse Parameter
Example 6: Descending order for numbers
numbers_desc = sorted([8, 3, 1, 6, 4], reverse=True)
print(numbers_desc) # Output: [8, 6, 4, 3, 1]Example 7: Descending order for strings
words_desc = sorted(["hello", "world", "python"], reverse=True)
print(words_desc) # Output: ['python', 'world', 'hello']Composite Sorting – Multiple Criteria
Example 8: Sort first by length, then alphabetically
items = ["apple", "banana", "pear", "orange"]
sorted_complex = sorted(items, key=lambda x: (len(x), x))
print(sorted_complex) # Output: ['pear', 'apple', 'orange', 'banana']Real‑World Applications
Example 9: Sorting a list of dictionaries by a field
students = [
{"name": "Tom", "grade": 88},
{"name": "Jerry", "grade": 92},
{"name": "Spike", "grade": 76}
]
sorted_students = sorted(students, key=lambda s: s["grade"], reverse=True)
print(sorted_students)
# Output: [{'name': 'Jerry', 'grade': 92}, {'name': 'Tom', 'grade': 88}, {'name': 'Spike', 'grade': 76}]Example 10: Counting word frequencies and sorting them
from collections import Counter
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
word_counts = Counter(words)
sorted_word_counts = sorted(word_counts.items(), key=lambda item: item[1], reverse=True)
print(sorted_word_counts)
# Output: [('the', 2), ('quick', 1), ('brown', 1), ('fox', 1), ('jumps', 1), ('over', 1), ('lazy', 1), ('dog', 1)]Conclusion
The sorted() function’s flexibility—from simple ascending sorts to complex multi‑criteria ordering—makes it indispensable for data analysis, text processing, and everyday programming tasks. Mastering its key and reverse parameters enables cleaner, more 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.
