Python sorted() Function

The sorted() function in Python returns the sorted list of an iterable object such as list, tuple, string, dictionary, set etc. For example:

x = [1, 5, 2, 4, 3]
print(sorted(x))

x = ['p', 'y', 't', 'h', 'o', 'n']
print(sorted(x))

The output produced by above program is given below:

[1, 2, 3, 4, 5]
['h', 'n', 'o', 'p', 't', 'y']

Python sorted() Function Syntax

The syntax of sorted() function in Python is:

sorted(iterable, key=None, reverse=False)

The first parameter, the iterable parameter is required, whereas the other two parameters are optional.

The default value of key parameter is None, whereas the default value of reverse parameter is False.

Note: Providing reverse=True, sorts the list, but in descending order.

Note: The key parameter helps a lot when we need to sort the string iterable, based on length, instead of alphabetical order. Also we can specify the function as value of key parameter like key=myfun, to define the sorting criteria.

Python sorted() Function Example

The program given below shows the simple example of sorted() function:

x = ('p', 'y', 't', 'h', 'o', 'n')
print(sorted(x))

x = "fresherearth"
print(sorted(x))

x = {'c', 'o', 'd', 'e', 's'}
print(sorted(x))

x = ("codes", "cracker", "dot", "com")
print(sorted(x))

x = {"Year": 2021, "Month": "Nov", "Day": "Sat"}
print(sorted(x))

Following is the output produced by above program:

['h', 'n', 'o', 'p', 't', 'y']
['a', 'c', 'c', 'c', 'd', 'e', 'e', 'k', 'o', 'r', 'r', 's']
['c', 'd', 'e', 'o', 's']
['codes', 'com', 'cracker', 'dot']
['Day', 'Month', 'Year']

Python sorted() Function with reverse=True Parameter

The program given below shows the simple example that uses the sorted() function with reverse=True parameter:

x = {'c', 'o', 'd', 'e', 's'}
print(sorted(x, reverse=True))

x = ("codes", "cracker", "dot", "com")
print(sorted(x, reverse=True))

x = {"Year": 2021, "Month": "Nov", "Day": "Sat"}
print(sorted(x, reverse=True))

Now the output will exactly be:

['s', 'o', 'e', 'd', 'c']
['dot', 'cracker', 'com', 'codes']
['Year', 'Month', 'Day']

Python sorted() Function with key=len Parameter

Here is an example of sorted() function with key=len parameter:

x = ("codes", "cracker", "dot", "com")
print(sorted(x, key=len))

The output will be:

['dot', 'com', 'codes', 'cracker']

Python Online Test


« Previous Function Next Function »