The sorted()
function in python returns a sorted list of the iterable object i.e. list, dictionary, and tuple. By default, it sorts the given object in ascending order.
In the case of strings and characters, sorting is done based on their ASCII values.
tuple = (2, -1, 7, 5)list = sorted(tuple)print(list)
sorted()
The Python sorted()
uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort.
sorted(iterable_object, key=key, reverse=False)
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.
touple1 = (2, -1, 7, 5)print(sorted(touple1, reverse=True)) # Sort the list in descending order# A callable function which returns the length of a stringdef lengthKey(str):return len(str)touple2 = ("London", "Paris", "Copenhagen", "Melbourne")# Sort based on the length of the elementsprint(sorted(touple2, key=lengthKey))
Free Resources