PythonLists and tuples
list. sort()
Sorts a list in place.
- Returns
None- Changes the original
- Yes
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 whenTrue.
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 afterz. Use thelocalemodule or thePyICUlibrary for proper alphabetical order.
Related entries
#- 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.
- sorted()Returns a new, sorted list built from the items of any collection.
- list.reverse()Reverses the order of the items in a list in place.
- lambdaA short anonymous function written as a single expression.
Spotted a mistake or missing an example? Write to us.