Python List sort() Method

Sorts the items of the list

Usage

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

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

Syntax

list.sort(key,reverse)

Python list sort() method parameters
ParameterConditionDescription
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.

Example: Sort the list of strings

L = ['red', 'green', 'blue', 'orange']
L.sort()
print(L)    # ['blue', 'green', 'orange', 'red']

Example: Sort the list of numbers

L = [42, 99, 1, 12]
L.sort()
print(L)    # [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.

Example: Trying to sort the list of numbers and strings

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

Sort List in Reverse Order

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

Example: Sort list in reverse order

L = ['red', 'green', 'blue', 'orange']
L.sort(reverse=True)
print(L)    # ['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.

Example: Sort a list by the length of the items

L = ['red', 'green', 'blue', 'orange']
L.sort(key=len)
print(L)    # ['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.

Example: 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)]
L.sort(key=myFunc)
print(L)	# [('Max', 25), ('Bob', 30), ('Sam', 35)]

Example: 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}]
L.sort(key=myFunc)
print(L)
# [{'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.

Example: Sort list case-sensitive

L = ['Red', 'Green', 'blue', 'orange']
L.sort()
print(L)    # ['Green', 'Red', 'blue', 'orange']

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

Example: Sort list case-insensitive

L = ['Red', 'Green', 'blue', 'orange']
L.sort(key=str.lower)
print(L)    # ['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.

Example: Get a sorted copy of the list with sorted()

L = ['red', 'green', 'blue', 'orange']
x = sorted(L)
print(x)    # ['blue', 'green', 'orange', 'red']

Example: Iterate through a sorted list without changing the original

L = ['red', 'green', 'blue', 'orange']
for x in sorted(L):
    print x
# 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.