Python List sort()

The sort() method sorts the elements of a given list.

The sort() method sorts the elements of a given list in a specific order - Ascending or Descending.

The syntax of sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.


sort() Parameters

By default, sort() doesn't require any extra parameters. However, it has two optional parameters:

  • reverse - If true, the sorted list is reversed (or sorted in Descending order)
  • key - function that serves as a key for the sort comparison

Return value from sort()

sort() method doesn't return any value. Rather, it changes the original list.

If you want the original list, use sorted().


Example 1: Sort a given list

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels
vowels.sort()

# print vowels
print('Sorted list:', vowels)

When you run the program, the output will be:

Sorted list: ['a', 'e', 'i', 'o', 'u']

How to sort in Descending order?

sort() method accepts a reverse parameter as an optional argument.

Setting reverse=True sorts the list in the descending order.

list.sort(reverse=True)

Alternately for sorted(), you can use the following code.

sorted(list, reverse=True)

Example 2: Sort the list in Descending order

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels
vowels.sort(reverse=True)

# print vowels
print('Sorted list (in Descending):', vowels)

When you run the program, the output will be:

Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

How to sort using your own function with key parameter?

If you want your own implementation for sorting, sort() also accepts a key function as an optional parameter.

Based on the results of the key function, you can sort the given list.

list.sort(key=len)

Alternatively for sorted

sorted(list, key=len)

Here, len is the Python's in-built function to count the length of an element.

The list is sorted based on the length of its each element, from lowest count to highest.

Example 3: Sort the list using key

# take second element for sort
def takeSecond(elem):
    return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key
random.sort(key=takeSecond)

# print list
print('Sorted list:', random)

When you run the program, the output will be:

Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]