Exploring Python's sorted Function in Depth

In Python programming, the sorted() function is a highly useful built-in function for sorting iterable objects. This article delves into the usage, parameters, and example applications of the sorted function.

1. Basic Usage

The basic syntax of the sorted() function is as follows:

sorted(iterable, key=None, reverse=False)

Parameter explanations:

  • iterable: The iterable object to be sorted, such as a list, tuple, or dictionary.
  • key: An optional parameter specifying a sorting key function, which can be a lambda expression, for example, sorting by a particular attribute value.
  • reverse: A optional parameter indicating whether to sort in ascending (False, default) or descending (True) order.

2. Example Applications

Here are several example applications showcasing the flexibility and power of the sorted function:

Example 1: Sorting a list

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

Example 2: Sorting by dictionary values

student_scores = {'Alice': 85, 'Bob': 70, 'Cathy': 92, 'David': 78}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)

3. Advanced Usage

Beyond basic sorting, the sorted function supports more complex scenarios, such as custom sorting rules and multi-key sorting. By leveraging the key parameter, you can achieve various customized sorting needs.

# Suppose we have a list of dictionaries, each containing name, age, and score
students = [
    {'name': 'Alice', 'age': 20, 'score': 85},
    {'name': 'Bob', 'age': 22, 'score': 70},
    {'name': 'Cathy', 'age': 21, 'score': 92},
    {'name': 'David', 'age': 19, 'score': 70}
]

# Use sorted for multi-key sorting: first by score descending, then by age ascending
sorted_students = sorted(students, key=lambda x: (-x['score'], x['age']))

# Print the sorted results
for student in sorted_students:
    print(student)

4. Summary

Through this article, we have gained an in-depth understanding of the usage and application scenarios of the sorted function in Python. The sorted function is a common sorting tool in Python that helps us quickly and flexibly sort data, improving programming efficiency.

Tags: python sorted Sorting programming

Posted on Sat, 19 Sep 2026 16:55:10 +0000 by Thora_Fan