English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python List sort() Usage and Example

Python list methods

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

The sort() method sorts the elements of the given list in a specific order (ascending or descending).Listto sort the elements of the list.

The syntax of the sort() method is:

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

In addition, you can also use Python's built-in function for the same purposesorted().

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

Note: The simplest difference between sort() and sorted() is: sort() does not return any value, while sorted() returns an iterable list.

sort() parameters

By default, sort() does not require any other parameters. However, it has two optional parameters:

  • reverse -If true, the sorted list will be reversed (or sorted in descending order)

  • key -Function used as the sorting comparison key

The return value of sort()

The sort() method does not return any value. Instead, it modifies the original list.

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

Example1Sort the given list

# Vowel list
vowels = ['e', 'a', 'u', 'o', 'i']
# Sort the vowels
vowels.sort()
# Print vowels
print('Sorted list:', vowels)

When running the program, the output is:

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

How to sort in descending order?

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

Set reverse=True to sort the list in descending order.

list.sort(reverse=True)

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

sorted(list, reverse=True)

Example2:Sort the list in descending order

# Vowel list
vowels = ['e', 'a', 'u', 'o', 'i']
# Vowel sorting
vowels.sort(reverse=True)
# Print vowels
print('Sorted list (in descending order):', vowels)

When running the program, the output is:

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

How to sort using your own function and key parameter?

If you want to sort with your own method, sort() can also take the key function as an optional parameter.

You can sort the given list according to the result of the key function.

list.sort(key=len)

It can also be sorted

sorted(list, key=len)

Here, len is a built-in function of Python, used to calculate the length of an element.

This list is sorted according to the length of each element (from the lowest to the highest count).

Example3:Sort the list by key

# Sort by the second element
def takeSecond(elem):
    return elem[1]
# Random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# Key sort list
random.sort(key=takeSecond)
# Print the list
print('Sorted list:', random)

When running the program, the output is:

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

Python list methods