Sorted Function

Last Updated: 02th September 2025


A sorted function is a function that returns a sorted list of elements from an iterable.

Syntax:

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

Example 1.

# sort a list of numbers
numbers = [3, 1, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 2, 3]

Example 2.

# sort a list of strings based on their length
words = ["apple", "banana", "cherry"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # ['apple', 'cherry', 'banana']

Example 3.

# sort a list of dictionaries based on a score
students = [
    {"name": "Aman", "score": 85},
    {"name": "Riya", "score": 92},
    {"name": "Karan", "score": 78}
]

sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
print(sorted_students)