Python sort() vs sorted(): Sort a List
There are two ways to sort. list.sort() changes the order of that list itself. sorted(list) leaves the original alone and returns a new sorted list. Both take the same key (what to sort by) and reverse (backwards) arguments.
list.sort(key=None, reverse=False)
new_list = sorted(iterable, key=None, reverse=False)
The difference between sort() and sorted()
Use sort() if you no longer need the original order, and sorted() if you need to keep it.
a = [3, 1, 2]b = sorted(a)print(a, b) a.sort()print(a)print(sorted("banana"))print(sorted((5, 4, 6)))[3, 1, 2] [1, 2, 3] [1, 2, 3] ['a', 'a', 'a', 'b', 'n', 'n'] [4, 5, 6]
Only lists have sort(). sorted() also accepts strings, tuples and sets, but the result is always a list.
reverse: largest first
Pass reverse=True for descending order. Strings are sorted in dictionary order (by character code), so uppercase letters come before lowercase ones.
nums = [5, 2, 9, 1]print(sorted(nums, reverse=True)) words = ["pear", "Kiwi", "apple"]print(sorted(words))print(sorted(words, reverse=True))[9, 5, 2, 1] ['Kiwi', 'apple', 'pear'] ['pear', 'apple', 'Kiwi']
key: what to compare by
Give key a function. Python calls that function once for each value and compares the results. The values stored in the list do not change.
words = ["pear", "Kiwi", "fig", "apple"]print(sorted(words, key=len))print(sorted(words, key=str.lower)) nums = ["10", "9", "100"]print(sorted(nums, key=int))print(sorted([-3, 1, -2], key=abs))['fig', 'pear', 'Kiwi', 'apple'] ['apple', 'fig', 'Kiwi', 'pear'] ['9', '10', '100'] [1, -2, -3]
Write only the function name, without parentheses (key=len). Even when you sort with key=int, the results are still strings.
Sorting by several keys
If key returns a tuple, the items of the tuple are compared in order, starting from the first. The example below puts the highest scores first, and people with the same score in dictionary order by name. Put - in front of a number to make just that key descending.
people = [("lee", 80), ("kim", 95), ("park", 80), ("choi", 95)]ranked = sorted(people, key=lambda p: (-p[1], p[0]))for name, score in ranked: print(score, name)95 choi 95 kim 80 lee 80 park
Equal values keep their original order
Python's sort is a stable sort. Values with the same key keep the order they had before sorting. Below, kiwi and plum have the same length, and so do fig and yam, so each pair comes out in its original order.
words = ["kiwi", "fig", "plum", "yam", "apple"]print(sorted(words, key=len))['fig', 'yam', 'kiwi', 'plum', 'apple']
Common mistakes
Storing the result of sort() in a variable
nums = [3, 1, 2]
nums = nums.sort()
print(nums)
→ None, not the sorted list
sort() changes the list in place and returns nothing. Write just nums.sort(), or write nums = sorted(nums).
Calling sorted() without keeping the result
nums = [3, 1, 2]
sorted(nums)
print(nums)
→ Still [3, 1, 2]
sorted() does not touch the original list. Store the new list it returns in a variable.
Sorting numbers from input while they are still strings
nums = input().split()
print(sorted(nums))
→ ['10', '100', '25', '9'] — not in numeric order
Strings are compared from the first character, so "100" comes before "25". Convert to numbers first with list(map(int, input().split())) and then sort, or pass key=int.
Sorting a list that mixes numbers and strings
print(sorted([3, "a", 1]))
→ TypeError: '<' not supported between instances of 'str' and 'int'
You can't sort when the list mixes types that can't be compared with each other. Make them all one type, or pass a key that turns everything into the same type, such as key=str.