Python sorted() Function
sorted(iterable, key=None, reverse=False) returns a new sorted list and leaves the original untouched; it works on any iterable.sorted() is the all-purpose sorting tool. Give it a list, tuple, set, dictionary, string or generator and you get back a fresh list in order. Because the original is never changed, it is safe to use when you still need the unsorted data, or when the source has no sort() method, such as a tuple or a set.
The sorting lesson covers the ideas in more depth, and sort() vs sorted() explains when to pick each.
| Syntax | sorted(iterable, /, *, key=None, reverse=False) |
|---|---|
| Parameters | iterable: items to sort; key: function giving the sort value; reverse: True for descending order |
| Returns | A new list |
| Time complexity | O(n log n); the sort is stable |
How sorted() orders numbers, strings and tuples
Numbers sort by value and strings by Unicode code point, so every uppercase letter comes before every lowercase one: "Zoe" sorts before "asha". Tuples sort by their first element, then the second. The result is always a list, whatever you passed in.
print(sorted([5, 2, 9, 1]))
print(sorted("hello"))
print(sorted(["asha", "Zoe", "Ravi"]))
print(sorted((3, 1, 2), reverse=True))Sorting with key= and reverse=
key receives each item and returns the value to sort by. Use len for length, str.lower for case-insensitive order, or a lambda to pick a field. Returning a tuple sorts by several fields, and reverse=True flips the order. Because sorting is stable, items with equal keys keep their original relative order.
names = ["asha", "Zoe", "Ravi"]
print(sorted(names, key=str.lower))
words = ["fig", "banana", "kiwi", "apple"]
print(sorted(words, key=len))Both key and reverse must be written as keywords.
sorted() on dictionaries, sets and generators
Sorting a dictionary gives its sorted keys. Use .items() with a key function to order by value, which is the basis of sorting a dictionary by value. A set has no order of its own, so sorted(set) is the easy way to print it predictably. When the list is yours to change, list.sort() sorts in place and returns None.
Examples you can run
Press Run, then edit the code and run it again.
Sort without changing the original
The original list keeps its order.
scores = [72, 88, 95, 61]
print(sorted(scores))
print(sorted(scores, reverse=True))
print(scores)Expected output[61, 72, 88, 95]
[95, 88, 72, 61]
[72, 88, 95, 61]
Sort students by score, then by name
A tuple key sorts by score descending (negated) and breaks ties by name.
students = [("Ravi", 90), ("Asha", 90), ("Meera", 85)]
ranked = sorted(students, key=lambda s: (-s[1], s[0]))
for name, score in ranked:
print(name, score)Expected outputAsha 90
Ravi 90
Meera 85
Sort a dictionary by value
Sort the items by the second element and rebuild a dictionary.
stock = {"pen": 40, "book": 5, "bag": 12}
by_qty = sorted(stock.items(), key=lambda kv: kv[1])
print(by_qty)
print(dict(by_qty))
print(sorted(stock))Expected output[('book', 5), ('bag', 12), ('pen', 40)]
{'book': 5, 'bag': 12, 'pen': 40}
['bag', 'book', 'pen']
Common mistakes
Expecting sorted() to sort in place
✗ Wrong
cart = [3, 1, 2]
sorted(cart)
print(cart)✓ Right
cart = [3, 1, 2]
cart = sorted(cart)
print(cart)Assign the result, or use cart.sort() to change the list itself.
Passing key positionally
✗ Wrong
print(sorted(["bb", "a"], len))✓ Right
print(sorted(["bb", "a"], key=len))key is keyword-only. Write key=len.
Sorting mixed types
✗ Wrong
print(sorted([3, "1", 2]))✓ Right
print(sorted([3, "1", 2], key=int))Convert all values to one type, or use a key such as key=int.
Python sorted() Function: questions people ask
What is the difference between sort() and sorted() in Python?
sorted() returns a new list and accepts any iterable, while list.sort() changes the list in place and returns None.
How do I sort in descending order in Python?
Add reverse=True, as in sorted(scores, reverse=True).
Is sorted() stable?
Yes. Items that compare equal keep their original order, which lets you sort by one field and then another.
Keep learning
Step-by-step lessons:
Python SortingPython Lists
Related:
Python sort() vs sorted(): What Is the Difference?Python List sort() MethodHow to Sort a Dictionary by Value in PythonPython min() FunctionPython reversed() Function
More in built-in functions:
Python print() FunctionPython len() FunctionPython range() FunctionPython type() FunctionPython int() FunctionPython float() FunctionPython str() FunctionPython input() Function See all →