Python List sort() Method
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.
a = [5, 2, 9, 1, 5, 6]
# Sort the value in increasing order
a.sort()
print(a)
Output
[1, 2, 5, 5, 6, 9]
Table of Content
Syntax of sort() method
list_name.sort(key=None, reverse=False)
Parameter:
- key (Optional): This is an optional parameter that allows we to specify a function to be used for sorting. For example, we can use the len() function to sort a list of strings based on their length.
- reverse (Optional): This is an optional Boolean parameter. By default, it is set to False to sort in ascending order. If we set reverse=True, the list will be sorted in descending order.
Return:
- Python list sort() returns none.
Sorting List in descending order
To sort a list in descending order, we need to set the reverse parameter to True.
a = [5, 2, 9, 1, 5, 6]
# Sorting in Descending Order
a.sort(reverse=True)
print(a)
Output
[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.
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)
Output
['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).
a = [(1, 3), (2, 2), (3, 1)]
def fun(val):
return val[1]
a.sort(key=fun)
print(a)
Output
[(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:
a = ["apple", "banana", "kiwi", "cherry"]
a.sort(key=lambda x: x[-1])
print(a)
Output
['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.
Case Insensitive Sort
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)
Output
['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.
Important Points to Remember
- The sort() method modifies the list in place and returns None.
- The default behavior of sort() is ascending order. Use reverse=True to sort in descending order.
- The key parameter can be used for customizing the sorting logic.
- We can use sorted() method, if we need to create a new sorted list without altering the original.