It sorts the elements of a given list in a specific ascending or descending order.
1. Sort list in ascending order
Syntax:
List_name.sort()
Example:
list_1 = [6,4,5,2,3,1]
list_1.sort()
print(list_1)
Output: [1, 2, 3, 4, 5]
2. Sort list in descending order
Syntax:
list_name.sort(reverse = True)
Example:
list_1 = [6,4,5,2,3,1]
list_1.sort(reverse = True)
print(list_1)
Output: [6, 5, 4, 3, 2, 1]
3. Sort list using user defined order
It sorts according to user's choice.
Syntax:
list_name.sort(key=…, reverse=…)
Example:
def sort_first(val):
return val[1]
list_1 = [(1, 2), (3, 3), (1, 1)]
list_1.sort(key = sort_first)
print(list_1)
Output: [(1, 1), (1, 2), (3, 3)]