Understanding Python's Built-in sorted() Function

Core Concept

sorted() is Python's built-in function for sorting iterable collections. It always returns a new sorted list, and leaves the original input iterable unmodified.

Basic Syntax

sorted(iterable, *, key=None, reverse=False)
  • iterable: Any iterable object to be sorted, such as lists, tuples, strings, dictionaries, etc.
  • key: A optional parameter that accepts a single-argument function. This function is applied to every element before comparison to generate a custom sorting key. A common use case is key=len to sort elements by they length.
  • reverse: An optional boolean parameter. When set to True, sorting is done in descending order; the default False sorts in ascending order.

Usage Examples

Sort a numeric list
raw_nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_nums = sorted(raw_nums)
print(sorted_nums)  # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Sort characters in a string
input_str = "python"
sorted_chars = sorted(input_str)
print(sorted_chars)  # Output: ['h', 'n', 'o', 'p', 't', 'y']
Sort a list of strings by length
str_list = ["apple", "banana", "cherry", "date"]
sorted_by_length = sorted(str_list, key=len)
print(sorted_by_length)  # Output: ['date', 'apple', 'banana', 'cherry']
Sort in descending order
raw_nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_desc = sorted(raw_nums, reverse=True)
print(sorted_desc)  # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
Sort a ditcionary by value
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
sorted_names = sorted(student_grades, key=lambda name: student_grades[name])
print(sorted_names)  # Output: ['Charlie', 'Alice', 'David', 'Bob']
Sort custom class objects by attribute
class Student:
    def __init__(self, full_name, test_score):
        self.full_name = full_name
        self.test_score = test_score

student_group = [
    Student('Alice', 85),
    Student('Bob', 92),
    Student('Charlie', 78),
    Student('David', 88)
]

sorted_students = sorted(student_group, key=lambda s: s.test_score)
for student in sorted_students:
    print(f"{student.full_name}: {student.test_score}")

Output:

Charlie: 78
Alice: 85
David: 88
Bob: 92

Tags: python built-in functions Sorting sorted()

Posted on Tue, 19 May 2026 17:50:32 +0000 by Switch0r