The sort()
function is a member of the list data structure in Python. By default, it sorts the elements of a list in ascending order.
list = [20, 5, -10, 300]list.sort()print(list)
In the case of strings and characters, sorting is done based on their ASCII values.
The Python list sort()
has been using the Timsort algorithm since version 2.3.
This algorithm has a runtime complexity of O(n.logn).
The function has two optional attributes which can be used to specify a customized sort:
The key
attribute requires a callable function as its input. The function will specify the sorting criteria.
list1 = [20, 5, -10, 300]list1.sort(reverse=True) # Sort the list in descending order# A callable function which returns the length of a stringdef lengthKey(str):return len(str)list2 = ["London", "Paris", "Copenhagen", "Melbourne"]# Sort based on the length of the elementslist2.sort(key=lengthKey)print(list2)