English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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 sort() method does not return any value. Instead, it modifies the original list.
If you want the original list, please use sorted().
# 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']
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)
# 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']
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).
# 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)]