Python List sort() Function
The List sort()
method sorts the elements of the list in place.
By default, sort()
method arranges the elements in ascending order, but it can also sort them in descending order
or according to a custom sorting function, by specifying function's parameters .
Lists can only be sorted if their elements are comparable to each other!
Otherwise, a TypeError
exception is raised.
Syntax
my_list.sort(key, reverse)
sort() Parameters
Python List sort()
method parameters::
Parameter | Condition | Description |
---|---|---|
key | Optional | A function to specify the sorting criteria. Default value is None . |
reverse | Optional | Setting it to True sorts the list in reverse order. Default value is False . |
If used, both the arguments must be specified as keyword arguments.
For example:
my_list.sort(key=len) # sort using len function
my_list.sort(reverse=True) # sort in reverse order
my_list.sort(key=len, reverse=True) # sort using len function and in reverse order
A function to be used as key
must take a single value and return single value.
sort() Return Value
Python List sort()
function does not return any value: it modifies the original list.
Examples
Example 1: Sort a List
The sort()
method sorts the list of strings alphabetically (according to ASCII):
names = ['Tom', 'Anna', 'David', 'Ryan']
names.sort()
print(names) # Output: ['Anna', 'David', 'Ryan', 'Tom']
output
['Anna', 'David', 'Ryan', 'Tom']
and the list of numbers numerically:
numbers = [5, 6, 7, 1, 2, 3, 9, 8, 4, 0]
numbers.sort()
print(numbers) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Sort a List in Descending Order
You can sort a list in descending order by setting reverse
parameter to True
.
numbers = [5, 6, 7, 1, 2, 3, 9, 8, 4, 0]
numbers.sort(reverse=True)
print(numbers) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
output
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Example 3: Sort a List of Not Comparable Elements
You can not sort lists that have both numbers and strings in them, because Python does not know how to compare these values.
For example, this will raise a TypeError
:
names = ['Tom', 3, 'Anna', 1, 2, 'David', 'Ryan']
names.sort() # raises TypeError
output
Traceback (most recent call last):
File "main.py", line 2, in <module>
names.sort() # raises
TypeError: '<' not supported between instances of 'int' and 'str'
Example 4: Sort a List with Key parameters
The key
parameter is used for more complex custom sorting: the key
parameter allows to specify a function to be
executed on each list item before making the comparisons.
For example, with a list of strings, specifying key=len
(where len is
the len()
built-in function) sorts the strings by length,
from shortest to longest:
names = ['Tom', 'Anna', 'David', 'Ryan']
names.sort(key=len)
print(names) # Output: ['Tom', 'Anna', 'Ryan', 'David']
output
['Tom', 'Anna', 'Ryan', 'David']
::: note
Note that, in this example, the comparison is done only using the length and not the ASCII order of the characters! So, strings with same length appear in the result in the same order of the original list.
For example, Anna
and Ryan
have same length but their position in the original list is different:
names1 = ['Tom', 'Anna', 'David', 'Ryan']
names2 = ['Tom', 'Ryan', 'David', 'Anna']
names1.sort(key=len)
names2.sort(key=len)
print(names1) # Output: ['Tom', 'Anna', 'Ryan', 'David']
print(names2) # Output: ['Tom', 'Ryan', 'Anna', 'David']
output
['Tom', 'Anna', 'Ryan', 'David']
:::
Example 5: Sort with Custom Function
You can also pass to the sort()
function your own custom function as key
function. A key
function should take a
single argument and return a key to use for sorting.
For example, sort a list of students (as list of tuple) by age (second element of the tuple):
def sortByAge(e):
return e[1] # return age
students = [('Tom', 30),('Anna', 23), ('David', 25)]
students.sort(key=sortByAge)
print(students) # Output: [('Anna', 23), ('David', 25), ('Tom', 30)]
output
[('Anna', 23), ('David', 25), ('Tom', 30)]
For example, sort a list of dictionaries by age (where age is key in each dictionary with a corresponding value)
def sortByAge(e):
return e['age'] # return age
students = [{'name': 'Tom', 'age': 30},
{'name': 'Anna', 'age': 23},
{'name': 'David', 'age': 25}]
students.sort(key=sortByAge)
print(students) # Output: [{'name': 'Anna', 'age': 23}, {'name': 'David', 'age': 25}, {'name': 'Tom', 'age': 30}]
output
[{'name': 'Anna', 'age': 23}, {'name': 'David', 'age': 25}, {'name': 'Tom', 'age': 30}]
Example 6: Sort List with a Lambda Expression
A key
function may also be created with the lambda expression.
It allows us to in-line function definition.
For example, sort a list of students (as list of tuple) by age (second element of the tuple):
students = [('Tom', 30),('Anna', 23), ('David', 25)]
students.sort(key=lambda student: student[1])
print(students) # Output: [('Anna', 23), ('David', 25), ('Tom', 30)]
output
[('Anna', 23), ('David', 25), ('Tom', 30)]
Example 7: Sort List of String without Case-Sensitivity
By default, the sort()
method sorts the list in ASCII order rather than actual alphabetical order: this means
uppercase letters come before lowercase letters.
names = ['Tom', 'Anna', 'david']
names.sort()
print(names) # Output: ['Anna', 'Tom', 'david']
output
['Anna', 'Tom', 'david']
If you want to sort the values in regular alphabetical order, set key
to str.lower
: this allows the sort()
function to
treat all the list items as if they were lowercase without actually changing the values in the list.
names = ['Tom', 'Anna', 'david']
names.sort(key=str.lower)
print(names) # Output: ['Anna', 'david', 'Tom']
output
['Anna', 'david', 'Tom']
sort() method vs sorted() built-in function
The sort()
method does not return anything, it modifies the original list. If you do not want to modify the original
list, use sorted()
built-in function because it returns a
sorted copy of the list.
For example, get a sorted copy of the list with sorted() built-in function:
names = ['Tom', 'Anna', 'David']
sorted_names = sorted(names)
print(names) # Output: ['Tom', 'Anna', 'David']
output
['Tom', 'Anna', 'David']
For example, iterate through a sorted list without changing the original
names = ['Tom', 'Anna', 'David']
for name in sorted(names):
print(name)
output
Anna
David
Tom
Another difference is that:
- the
sort()
method is only defined for lists. - the
sorted()
function accepts ANY iterable like tuple, dictionary etc.
Moreover, the sort()
method doesn’t need to create a new list, so it’s faster between the two.