Python List sort() Method

Sorts the items of the list


Use sort() method to sort the items of the list.

You can optionally specify parameters for sort customization like sorting order and sorting criteria.



Python list sort() method parameters
keyOptionalA function to specify the sorting criteria.
Default value is None.
reverseOptionalSettting it to True sorts the list in reverse order.
Default value is False.

Please note that both the arguments must be specified as keyword arguments.

Sort List

sort() method sorts the list of strings alphabetically and the list of numbers numerically.

# Sort the list of strings
L = ['red', 'green', 'blue', 'orange']
# Prints ['blue', 'green', 'orange', 'red']
# Sort the list of numbers
L = [42, 99, 1, 12]
# Prints [1, 12, 42, 99]

However, you cannot sort lists that have both numbers and strings in them, since Python doesn’t know how to compare these values.

L = ['red', 'blue', 1, 12, 'orange',42, 'green', 99]
# Triggers TypeError: '<' not supported between instances of 'int' and 'str'

Sort List in Reverse Order

You can also sort the list in reverse order by setting reverse to TRUE.

L = ['red', 'green', 'blue', 'orange']
# Prints ['red', 'orange', 'green', 'blue']

Sort with Key

Use key parameter for more complex custom sorting. A key parameter specifies a function to be executed on each list item before making comparisons.

For example, with a list of strings, specifying key=len (the built-in len() function) sorts the strings by length, from shortest to longest.

L = ['red', 'green', 'blue', 'orange']
# Prints ['red', 'blue', 'green', 'orange']

A function to be used as key must take a single value and return single value.

Sort with Custom Function

You can also pass in your own custom function myFunc as the key function.

# Sort a list of tuples based on the age of students
def myFunc(e):
  return e[1]	# return age

L = [('Bob', 30),
     ('Sam', 35),
     ('Max', 25)]
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
# Sort a list of dictionaries based on the age of students
def myFunc(e):
    return e['age']		# return age

L = [{'name': 'Bob', 'age': 30},
     {'name': 'Sam', 'age': 35},
     {'name': 'Max', 'age': 25}]
# [{'age': 25, 'name': 'Max'}, {'age': 30, 'name': 'Bob'}, {'age': 35, 'name': 'Sam'}]

Case-insensitive Sorting

By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters.

# Case-sensitive sorting
L = ['Red', 'blue', 'Green', 'orange']
# Prints ['Green', 'Red', 'blue', 'orange']

If you want to sort the values in regular alphabetical order, set key to str.lower

# Case-insensitive sorting
L = ['Red', 'blue', 'Green', 'orange']
# Prints ['blue', 'Green', 'orange', 'Red']

This causes the sort() function to treat all the list items as if they were lowercase without actually changing the values in the list.

sort() vs sorted()

The sort() method doesn’t return anything, it modifies the original list (i.e. sorts in-place). If you don’t want to modify the original list, use sorted() function. It returns a sorted copy of the list.

# Get a sorted copy of the list with sorted()
L = ['red', 'green', 'blue', 'orange']
x = sorted(L)
# Prints ['blue', 'green', 'orange', 'red']
# Iterate through a sorted list without changing the original
L = ['red', 'green', 'blue', 'orange']
for x in sorted(L):
# Prints blue green orange red

Another difference is that the sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable like tuple, dictionary etc. Also, the sort() method doesn’t need to create a new list, so it’s faster between the two.