Python sorted() function
Return a new sorted list from any iterable.
Syntax
sorted(iterable, *, key=None, reverse=False)
The original is not changed. key gives a value to sort by for each item; reverse=True sorts largest first. Sorting is stable: items that compare equal keep their original order.
Parameters
| iterable | what to sort |
| key | function giving the value to sort by |
| reverse | True for descending order |
Return value
a new list
Example
Code
scores = [70, 92, 85] print(sorted(scores), scores) print(sorted(scores, reverse=True)) print(sorted("python")) words = ["Banana", "apple", "cherry"] print(sorted(words)) # capitals first print(sorted(words, key=str.lower)) # ignore case print(sorted(words, key=len))
Output
[70, 85, 92] [70, 92, 85] [92, 85, 70] ['h', 'n', 'o', 'p', 't', 'y'] ['Banana', 'apple', 'cherry'] ['apple', 'Banana', 'cherry'] ['apple', 'Banana', 'cherry']
Good to know.
list.sort() sorts in place and returns None; sorted() returns a new list.Related
Learn it step by step in the free lesson Lists & Tuples, with exercises that check your answers.