← Python lessons

Python Sorting: sorted() with reverse and key

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

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.

🎯 Goal — make it print exactly:
[30, 18, 12, 5]
times = [12, 30, 5, 18]# add one line: print times sorted biggest first

Advanced reading

Practise this lesson

This exercise uses this lesson. It runs in your browser and checks your code instantly — no sign-up needed.

API basics