sorted()
sorted(iterable, /, *, key=None, reverse=False) list · Updated March 13, 2026 · Built-in Functions The sorted() function takes any iterable and returns a new list containing all items from the iterable in sorted order. Unlike the list.sort() method which modifies the list in-place, sorted() leaves the original iterable unchanged and returns a brand new list. This makes it useful for sorting tuples, strings, dictionaries, generators, and any other iterable type.
Syntax
sorted(iterable, /, *, key=None, reverse=False)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
iterable | iterable | — | Any iterable to sort (list, tuple, string, dict, set, generator, etc.). Items must be mutually comparable. |
key | callable | None | A function of one argument used to extract a comparison key from each element. If None, elements are compared directly. |
reverse | bool | False | If True, the list is sorted in descending order instead of ascending. |
Returns: A new list containing all items from the iterable in sorted order.
Examples
Basic usage
Sort a list of numbers in ascending order:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# [1, 2, 5, 8, 9]
# Original list remains unchanged
print(numbers)
# [5, 2, 8, 1, 9]
Sorting in descending order
Use the reverse parameter to sort in descending order:
fruits = ["banana", "apple", "cherry", "date"]
sorted_fruits = sorted(fruits, reverse=True)
print(sorted_fruits)
# ['date', 'cherry', 'banana', 'apple']
Using the key parameter
Sort by a specific attribute or transformation:
# Sort strings by length
words = ["cat", "elephant", "dog", "hippopotamus"]
by_length = sorted(words, key=len)
print(by_length)
# ['cat', 'dog', 'elephant', 'hippopotamus']
# Sort tuples by the second element
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
by_second = sorted(pairs, key=lambda x: x[1])
print(by_second)
# [(1, 'one'), (3, 'three'), (2, 'two')]
Sorting with case-insensitive comparison
Sort strings regardless of case:
names = ["Alice", "bob", "CHARLIE", "diana"]
case_insensitive = sorted(names, key=str.lower)
print(case_insensitive)
# ['Alice', 'bob', 'CHARLIE', 'diana']
Sorting a dictionary
Sorting a dictionary returns the sorted keys:
ages = {"Alice": 30, "Bob": 25, "Charlie": 35}
sorted_keys = sorted(ages)
print(sorted_keys)
# ['Alice', 'Bob', 'Charlie']
# Sort by values
sorted_by_age = sorted(ages.keys(), key=lambda k: ages[k])
print(sorted_by_age)
# ['Bob', 'Alice', 'Charlie']
Sorting with custom objects
Sort objects by a specific attribute:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person({self.name}, {self.age})"
people = [Person("Charlie", 35), Person("Alice", 25), Person("Bob", 30)]
sorted_by_age = sorted(people, key=lambda p: p.age)
print(sorted_by_age)
# [Person(Alice, 25), Person(Bob, 30), Person(Charlie, 35)]
Common Patterns
Sorting with multiple criteria (stable sort)
Python’s sort is stable, meaning equal keys preserve their original order:
data = [("apple", 3), ("banana", 1), ("cherry", 2), ("date", 1)]
# First sort by number, then by name for equal numbers
sorted_data = sorted(data, key=lambda x: (x[1], x[0]))
print(sorted_data)
# [('banana', 1), ('date', 1), ('cherry', 2), ('apple', 3)]
Getting the smallest or largest N elements
Combine sorted() with slicing for top-N selection:
scores = [89, 95, 72, 88, 91, 82, 76, 90]
# Top 3 scores
top_3 = sorted(scores, reverse=True)[:3]
print(top_3)
# [95, 91, 90]
# Bottom 3 scores
bottom_3 = sorted(scores)[:3]
print(bottom_3)
# [72, 76, 82]
Sorting iterables that aren’t lists
Convert and sort any iterable:
# Sort a tuple
coordinate = (3, 1, 2)
print(sorted(coordinate))
# [1, 2, 3]
# Sort a string (returns list of characters)
word = "python"
print(sorted(word))
# ['h', 'n', 'o', 'p', 't', 'y']
# Sort a set
unique_numbers = {5, 2, 8, 1, 9}
print(sorted(unique_numbers))
# [1, 2, 5, 8, 9]
Using operator.attrgetter or itemgetter
More efficient than lambda for object or item access:
from operator import itemgetter, attrgetter
# Sort tuples by second element (more efficient than lambda)
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=itemgetter(1))
print(sorted_pairs)
# [(1, 'one'), (3, 'three'), (2, 'two')]
# Sort with multiple keys
data = [(1, 'apple', 5), (2, 'banana', 3), (1, 'cherry', 7)]
sorted_data = sorted(data, key=itemgetter(0, 2))
print(sorted_data)
# [(1, 'apple', 5), (1, 'cherry', 7), (2, 'banana', 3)]
Errors
TypeError: ’<’ not supported between instances
Items must be mutually comparable:
# This raises TypeError
mixed = [1, "two", 3]
sorted(mixed)
# TypeError: '<' not supported between instances of 'str' and 'int'
# Solution: use key to convert to comparable types
sorted(mixed, key=str)
# [1, 3, 'two']
TypeError: ‘NoneType’ object is not callable
The key parameter must be a callable, not the result of a function call:
# Wrong: calling str.lower instead of passing it
numbers = [3, 1, 2]
sorted(numbers, key=str.lower()) # TypeError!
# Correct: pass the function itself
sorted(numbers, key=str) # Works