Python Tutorial Python Advanced Python References Python Libraries

Python sorted() Function



The Python sorted() function is used to sort elements of an iterable in ascending or descending order. In this function, a function can be passed as optional parameter to specify sorting criteria.

Syntax

sorted(iterable, reverse = True | False, key = function)

Parameters

iterable Required. iterable object like list, tuple, set, string , dictionary and range() etc.
reverse Optional. takes either 'True' or 'False' values. Default value is False. True is used for descending order sorting and False is used for ascending order sorting.
key Optional. A function which specify sorting criteria.

Example: Reverse order Sorting

In the example below, sorted() function is used to sort elements of a list in reverse order.

MyList = [1, 10, 5, 7, 3, 6, 5]
x = sorted(MyList, reverse = True)  
print(x)

The output of the above code will be:

[10, 7, 6, 5, 5, 3, 1]

Example: Reverse order Sorting with function criteria

This example describes how to use sorted() function to sort elements of a list in reverse order based on the length of the element.

def name_length(x):
  return len(x)

MyList = ['Marry', 'Sam', 'John', 'Jo']
# sort 'MyList' list based on name_length() function
x = sorted(MyList, reverse = True, key = name_length)  
print(x)

The output of the above code will be:

['Marry', 'John', 'Sam', 'Jo']

❮ Python Built-in Functions