Last Updated : 11 Jul, 2025
The sort() method in Python is a built-in function that allows us to sort the elements of a list in ascending or descending order and it modifies the list in place which means there is no new list created. This method is useful when working with lists where we need to arranged the elements in a specific order, whether numerically or alphabetically.
Below is a simple example that use sort() method to arrange a list of integer values in ascending order.
Python
a = [5, 2, 9, 1, 5, 6]
# Sort the value in increasing order
a.sort()
print(a)
[1, 2, 5, 5, 6, 9]Syntax of sort() method
list_name.sort(key=None, reverse=False)
Parameter:
Return:
To sort a list in descending order, we need to set the reverse parameter to True.
Python
a = [5, 2, 9, 1, 5, 6]
# Sorting in Descending Order
a.sort(reverse=True)
print(a)
[9, 6, 5, 5, 2, 1]Custom sorting using key parameter
We can sort a list using a custom key by defining a function that specifies the sorting rule. For example, if we have a list of strings and want to sort them by length then we can use key=len. This will arrange the words from shortest to longest.
Python
a = ["apple", "banana", "kiwi", "cherry"]
# The key=len tells the sort() method
# to use length of each string during sorting
a.sort(key=len)
print(a)
['kiwi', 'apple', 'banana', 'cherry']Sorting with a Custom Function
We can also define our custom sorting function to control the sorting behavior. In the the below example, we are sorting a list of tuples by the second element (those tuple whose second value are smaller would come first).
Python
a = [(1, 3), (2, 2), (3, 1)]
def fun(val):
return val[1]
a.sort(key=fun)
print(a)
[(3, 1), (2, 2), (1, 3)]
We can also use a lambda function as a key to define more complex sorting rules. For example, sorting a list of strings based on the last character:
Python
a = ["apple", "banana", "kiwi", "cherry"]
a.sort(key=lambda x: x[-1])
print(a)
['banana', 'apple', 'kiwi', 'cherry']
Explanation: Here, we used key=lambda x: x[-1]
to sort the strings based on their last character. The result is ['banana', 'apple', 'cherry', 'kiwi']
, ordered by the last letter of each word.
By default, the sort()
method is case sensitive, resulting in all capital letters being sorted before lowercase letters. To perform a case insensitive sort, we can use the str.lower
function as the key.
a = ["Banana", "apple", "Grape", "pear"]
a.sort(key=str.lower)
print(a)
['apple', 'Banana', 'Grape', 'pear']
Explanation: In this example, we used key=str.lower
to make sure that the sorting is case insensitive. This means that all words are treated as lowercase during sorting.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4