Python Sorting: sorted() with reverse and key
Sorting in Python puts values in order. sorted() takes a list and gives back a new list in order, smallest first.
This is an extension beyond the core Python concepts. Read Lists first.
Sorting a list
scores = [7, 2, 9, 4]print(sorted(scores))print(sorted(scores, reverse=True))print(scores)reverse=True sorts biggest first. The last line shows scores is unchanged. sorted() made a new list.
Sorting by a key function
key= tells sorted() what to compare. Give it a function name, such as len.
names = ["Maya", "Bo", "Alexandra"]print(sorted(names, key=len))This prints ['Bo', 'Maya', 'Alexandra'], shortest name first. Write len with no brackets. sorted() calls it on each name for you.
Equal keys keep their order
When two items have the same key, they stay in their original order.
names = ["Zoe", "Amy", "Bo"]print(sorted(names, key=len))This prints ['Bo', 'Zoe', 'Amy']. Zoe and Amy both have three letters, so Zoe stays first.
See also: Lists, Dictionaries.
Your turn
Print times sorted from biggest to smallest.
[30, 18, 12, 5]
times = [12, 30, 5, 18]# add one line: print times sorted biggest firstAdvanced reading
- List methods — sort a list in place with
sort()and see why it returnsNone. - Sorting dictionaries and breaking ties — rank dictionary keys by their values and keep only the top few.
- Lambda functions — write your own one-line key, such as the last letter of a word.