The sort() function in python helps to sort the list in user-defined order(ascending or descending). By default, sort works in ascending order.
list.sort(key=..., reverse=...) #where key is function name
This function takes two optional parameters. We can also use the sorted(list, key=..., reverse=...) method for the same purpose. The difference is that the sorted() method doesn't change the list and return a sorted list, but the sort() method directly changes the list and doesn't return any value.
Parameter | Description | Required / Optional |
---|---|---|
reverse | If True, the sorted list is reversed (or in Descending order) | Optional |
key | function that serves as a key for the sort comparison | Optional |
The sort() method doesn't return any value. It updates the original list by making changes in the order of the elements. For returning sorted list without changing the original list we can use the sorted() method.
# alphabets list
alphabets = ['b', 'a', 'e', 'd', 'c']
# sort the alphabets
alphabets.sort()
# print alphabets
print('Sorted list:', alphabets)
Output:
Sorted list: ['a', 'b', 'c', 'd', 'e']
# alphabets list
alphabets = ['b', 'a', 'e', 'd', 'c']
# sort the alphabets
alphabets.sort(reverse=True)
# print alphabets
print('Sorted list in Descending order:', alphabets)
Output:
Sorted list in Descending order: ['e', 'd', 'c', 'b', 'a']
# take second element for sort
def second(elem):
return elem[1]
# random list
randomlist = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
randomlist.sort(key=second)
# print list
print('Sorted list:', randomlist)
Output:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]