What is the Python sorted() function?

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.

svg viewer
tuple = (2, -1, 7, 5)
list = sorted(tuple)
print(list)

Algorithm used by sorted()

The Python sorted() uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort.

Syntax


sorted(iterable_object, key=key, reverse=False)

The function has two optional attributes which can be used to specify a customized sort:

svg viewer

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 string
def lengthKey(str):
return len(str)
touple2 = ("London", "Paris", "Copenhagen", "Melbourne")
# Sort based on the length of the elements
print(sorted(touple2, key=lengthKey))

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved