Javatpoint Logo
Javatpoint Logo

Python sorted() Function

Python sorted() function is used to sort elements. By default, it sorts elements in ascending order but can be sorted descending also. It takes four arguments and returns collection in sorted order. In the case of a dictionary, it sorts only keys, not values. The signature of the function is given below.



iterable: A collection on which sorting performs.

cmp: A custom comparison function. The default value is None.

key: A function.

reverse: To get sorted collection in reverse order.


It returns a unique integer number.

Let's see some examples of id() function to understand it's functionality.

Python sorted() Function Example 1

Here, in this example, we are sorting a string object to understand the function.


['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']

Python sorted() Function Example 2

We can use this function to sort any iterable like list, tuple and dictionary. See the example below.


[56, 98, 622, 659, 1002, 2003, 3652]
[21, 232, 2500, 2578, 3698, 5264]
[1, 2, 3, 4]

Python sorted() Function Example 3

To sort the list into reverse order (descending), pass True in reverse, and we will get the list sorted in reverse order.


[3652, 2003, 1002, 659, 622, 98, 56]

Python sorted() Function Example 4

Here, we are sorting a list by passing a lambda function in the key during the call.


[(3, 5), (8, 5), (2, 15), (65, 5)]

Next TopicPython Set

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA