Master Python’s sorted() Function: Simple to Advanced Sorting Techniques
This article walks through Python’s built‑in sorted() function, covering basic ascending and descending sorts, custom key functions for sorting complex iterables like lists of dictionaries, and using filter() to extract items, all illustrated with clear code examples and screenshots.
1. Introduction
A follower asked about sorting in Python, so this article shares how to use the built‑in sorted() function for everyday tasks.
2. Basic Usage
The sorted() function can sort a simple list in ascending order.
lst = [3, 28, 18, 29, 2, 5, 88]
result = sorted(lst)
print(result)Result: [2, 3, 5, 18, 28, 29, 88].
To sort in descending order, add the reverse=True argument.
lst = [3, 28, 18, 29, 2, 5, 88]
result = sorted(lst, reverse=True)
print(result)Result: [88, 29, 28, 18, 5, 3, 2].
3. Advanced Usage
When sorting more complex iterables such as a list of dictionaries, provide a custom key function.
lst = [
{"id": 1, "name": "鲁班", "age": 18},
{"id": 2, "name": "鲁班大师", "age": 26},
{"id": 3, "name": "鲁大师", "age": 23},
{"id": 4, "name": "狄仁杰", "age": 48}
]
# Sort by age in ascending order
sorted(lst, key=lambda x: x.get('age'))The sorted() function accepts three parameters: the iterable, a key function that determines the sort order, and a reverse flag (True for descending, False for ascending).
To extract items with age greater than or equal to 28, combine filter() with a lambda:
list(filter(lambda x: x['age'] >= 28, lst))4. Bonus: Deep and Shallow Copy
Additional notes on Python’s deep and shallow copy mechanisms are often asked in interviews and are useful for handling mutable objects.
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.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
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.
