sort() vs sorted()
list.sort() sorts the list in place and returns None, while sorted() returns a new, sorted list from any collection and leaves the original untouched.
Side-by-side comparison
#What it returns
- list.sort()
None- sorted()
- A new, sorted list
Changes the original
- list.sort()
- Yes, in place
- sorted()
- No
Works on
- list.sort()
- Only on a list
- sorted()
- Any iterable
The key and reverse parameters
- list.sort()
- Yes
- sorted()
- Yes
Stability of the sort
- list.sort()
- Yes
- sorted()
- Yes
Typical use
- list.sort()
- A list whose original order is no longer needed
- sorted()
- A tuple, a set, a string, or when the original must stay
Example
#scores = [72, 95, 64, 88]
scores.sort()
print(scores)
names = ("Mia", "emma", "Jack")
print(sorted(names, key=str.lower))
print(names)Definition and usage
#Both are for sorting, and both accept the same parameters: key with a function that computes a sort key, and reverse=True for descending order. Sorting is stable in both cases: elements with equal keys keep their relative order.
They differ in what happens to the data. The sort() method changes the list in place and returns None, so writing my_list = my_list.sort() turns the list into None. It only works on lists. The sorted() function creates a new list and returns it, without touching the original, and accepts any iterable: a list, a tuple, a set, or a string.
When the original order is no longer needed and you’re sorting a list, sort() is a bit faster, because it doesn’t create a new list. When you want to keep the original, you’re sorting something other than a list, or you need the result inside the same expression, for example in a for loop or a function argument, use sorted().
Syntax
#my_list.sort(key=None, reverse=False)
sorted(iterable, key=None, reverse=False)More examples
#tasks = ["c", "a", "b"]
tasks = tasks.sort()
print(tasks)word = "python"
print(sorted(word))
print(sorted(word, reverse=True))Good practices
#- If you want to sort a list without changing the original, use
sorted(my_list)instead of copying the list and callingsort(). - To sort by several criteria, give
keya tuple, e.g.key=lambda s: (-s["points"], s["name"]). - Accented letters sort after "z" by default. For correct sorting by locale, use the
localemodule or thePyICUlibrary.
Related entries
#Spotted a mistake or missing an example? Write to us.