ComparisonComparisons

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.

On this page

Side-by-side comparison

#

Example

#
Python
scores = [72, 95, 64, 88]
scores.sort()
print(scores)

names = ("Mia", "emma", "Jack")
print(sorted(names, key=str.lower))
print(names)
Resultsaved result, you can check it
[64, 72, 88, 95]
['emma', 'Jack', 'Mia']
('Mia', 'emma', 'Jack')

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

#
Syntax
my_list.sort(key=None, reverse=False)
sorted(iterable, key=None, reverse=False)

More examples

#
sort() returns None, don’t assign the result
Python
tasks = ["c", "a", "b"]
tasks = tasks.sort()
print(tasks)
Resultsaved result, you can check it
None
sorted() also works on strings
Python
word = "python"
print(sorted(word))
print(sorted(word, reverse=True))
Resultsaved result, you can check it
['h', 'n', 'o', 'p', 't', 'y']
['y', 't', 'p', 'o', 'n', 'h']

Good practices

#
  • If you want to sort a list without changing the original, use sorted(my_list) instead of copying the list and calling sort().
  • To sort by several criteria, give key a tuple, e.g. key=lambda s: (-s["points"], s["name"]).
  • Accented letters sort after "z" by default. For correct sorting by locale, use the locale module or the PyICU library.

Related entries

#

Spotted a mistake or missing an example? Write to us.