list.sort()

Sorts a list in place.

Returns
None
Changes the original
Yes
On this page

Example

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

names = ["mia", "Jack", "emma", "Nathaniel"]
names.sort(key=str.lower)
print(names)

names.sort(key=len, reverse=True)
print(names)
Resultsaved result, you can check it
[64, 72, 88, 95]
['emma', 'Jack', 'mia', 'Nathaniel']
['Nathaniel', 'emma', 'Jack', 'mia']

Definition and usage

#

The sort() method orders the items of the list, changing the list itself. It returns None, so writing my_list = my_list.sort() turns the list into None.

It takes the same parameters as the sorted() function: key, a function that computes the sort key, and reverse=True for descending order. The sort is stable.

If you do not want to change the original, or you are sorting something other than a list, use the sorted() function, which returns a new list.

Syntax

#
Syntax
list.sort(key=None, reverse=False)

Parameters

#
  • key

    function, optional

    A function that computes the sort key.
  • reverse

    bool, default False

    Descending order when True.

Good practices

#
  • To sort regardless of letter case, use key=str.lower.
  • Accented letters sort by Unicode code point by default, which can put them in a surprising place, for example é sorts after z. Use the locale module or the PyICU library for proper alphabetical order.

Related entries

#

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