Python List - sort() Method
The Python sort() method is used to sort elements of the list in ascending or descending order. This method has an optional argument which can be used to pass a function to specify sorting criteria.
Syntax
list.sort(reverse = True | False, key = function)
Parameters
reverse |
Optional. takes either 'True' or 'False' values. Default value is False. True is used for descending order sorting and False is used for ascending order sorting. |
key |
Optional. A function to specify sorting criteria. |
Return Value
None.
Example: Reverse order Sorting
In the example below, sort() method is used to sort all elements of the list called MyList in descending order.
MyList = [1, 10, 5, 7, 3, 6, 5] MyList.sort(reverse = True) print(MyList)
The output of the above code will be:
[10, 7, 6, 5, 5, 3, 1]
Example: Reverse order Sorting with function criteria
In the example below, a function called name_length() is used with list sort() method which specifies length of the element as sorting criteria.
def name_length(x): return len(x) MyList = ['Marry', 'Sam', 'John', 'Jo'] MyList.sort(reverse = True, key = name_length) print(MyList)
The output of the above code will be:
['Marry', 'John', 'Sam', 'Jo']
❮ Python List Methods