PythonArraysIntermediate

sorted()

Returns a new sorted list from any iterable (does not mutate input).

Review the syntaxStudy the examplesOpen the coding app
new_list = sorted(iterable, key=None, reverse=False)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Returns a new sorted list from any iterable (does not mutate input).

The sorted() function is a built-in Python utility that generates a new sorted list from any iterable (e.g., list, tuple, dictionary, or string). It implements the Timsort algorithm—a hybrid of merge sort and insertion sort—which provides a worst-case time complexity of O(n log n) and is guaranteed to be stable. Stability ensures that elements with identical sort keys maintain their relative original order, which is crucial for multi-pass sorting or complex data structures. Unlike the list.sort() method, which performs an in-place mutation and returns None, sorted() is a functional approach that returns a new list object, thus requiring O(n) additional space complexity. It supports a 'key' parameter for custom ordering via a callbackFn and a 'reverse' boolean for descending sorts. A common edge case involves sorting iterables with non-comparable types (like mixed integers and strings), which will raise a TypeError in Python 3.

Quick reference

Syntax

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

Inputs

Parameters

iterableIterable[Any] · Items to sort.
key (optional)Callable[[Any], Any] · Function that returns a value to sort by.
reverse (optional)bool · Sort descending if True.

See it in practice

Examples

1

Numeric Sorting in Descending Order

numbers = [42, 1, 15, 7]
result = sorted(numbers, reverse=True)
print(result)
Output:
[42, 15, 7, 1]

Sorts a list of integers in descending order using the reverse parameter.

2

Sorting Strings by Custom Key (Length)

words = ['banana', 'apple', 'cherry', 'kiwi']
# Use len as the callbackFn to sort by character count
result = sorted(words, key=len)
print(result)
Output:
['kiwi', 'apple', 'cherry', 'banana']

Demonstrates the use of a built-in function as a key to sort strings by length rather than alphabetically.

3

Sorting Complex Objects (Dictionaries)

users = [{'name': 'Max', 'age': 30}, {'name': 'Anna', 'age': 22}, {'name': 'Zoe', 'age': 22}]
# Sort by age, then by name (stability check)
result = sorted(users, key=lambda x: x['age'])
print(result)
Output:
[{'name': 'Anna', 'age': 22}, {'name': 'Zoe', 'age': 22}, {'name': 'Max', 'age': 30}]

Sorts a list of dictionaries by a specific value. Note that Anna remains before Zoe because the sort is stable.

Debug faster

Common Errors

1

TypeError

Cause: Attempting to sort an iterable containing incompatible data types that do not support the less-than operator between them.

Fix: Ensure all elements are of the same type or use a key function to normalize them for comparison.

sorted([10, '20', 30])
2

LogicError

Cause: Expecting the original list to be modified in-place, similar to the list.sort() method.

Fix: Assign the result of sorted() to a new variable or overwrite the original variable with the return value.

my_list = [3, 1, 2]
sorted(my_list)
print(my_list) # Still [3, 1, 2]

Runtime support

Compatibility

Python 3.8+

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Returns a new sorted list from any iterable (does not mutate input).

iterable: Items to sort. key: Function that returns a value to sort by. reverse: Sort descending if True.

TypeError: Ensure all elements are of the same type or use a key function to normalize them for comparison. LogicError: Assign the result of sorted() to a new variable or overwrite the original variable with the return value.