![]() |
VOOZH | about |
The sort() method is used to arrange the elements of a list in a specific order, either ascending or descending. It changes the original list directly, so no new list is created. This method works well for sorting numbers or strings.
Let’s sort a list of numbers in ascending order.
[1, 2, 3, 4]
Explanation: a.sort() arranges the list elements in increasing order, a is updated with the sorted values.
lst.sort(key=None, reverse=False)
Parameters:
By default, sort() arranges elements in ascending order. To sort values from highest to lowest, we use the reverse=True parameter.
[9, 6, 5, 5, 2, 1]
Explanation: reverse=True changes the sorting order to descending
The key parameter allows sorting based on a custom rule. For example, strings can be sorted by their length instead of alphabetical order.
['kiwi', 'apple', 'banana', 'cherry']
Explanation: key=len tells Python to compare items using their length. Shorter words appear first
When sorting tuples, you can sort based on a specific element inside each tuple.
[(3, 1), (2, 2), (1, 3)]
Explanation: x[1] means sorting is done using the second value of each tuple. Tuples with smaller second values come first
You can also define custom rules using a lambda function, such as sorting words by their last character.
['banana', 'apple', 'kiwi', 'cherry']
Explanation: x[-1] extracts the last character of each string. Sorting is based on that character
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.
['apple', 'Banana', 'Grape', 'pear']
Explanation: str.lower converts all values to lowercase for comparison. Original casing is preserved in the output