 Python Sorted()

The sorted() method in Python sorts the elements of a given iterable and outputs the sorted iterable as a list. You will have the flexibility to specify ascending or descending order. Numbers and strings are sorted accordingly. To make sorting easy for programmers there is an in-built function named Python sorted.

There are many instances that we will come across while programming where we will need to sort numbers and alphabets depending on the context of the problem we are solving. The in-built function named Sorted Python, does all the work for you. So, now let us get into the details of what is sorted() function in python, how it works, and how to use it.

Note: It is impossible to sort a list that contains both numeric values and string values.

Parameters for python sorted function

Syntax

 Sorted(iterable, key, reverse)

Parameters: sorted() function takes in three parameters of which two are optional.

• Iterable (required parameter): Sequence (tuple,string, list) or collection (set, dictionary, frozenset), etc.
• Key (optional parameter): A function that acts as a key to decide the order. There is no default value for this parameter.
• Reverse (optional parameter): It’s a boolean value, where True instructs the function to sort the list in descending order, while False instructs the function to sort the list in ascending order. False is the default value for this parameter.

Example 1: Sort string, list, and tuple

Now, let us sort a list, tuple, and string to clearly understand how sorted() works.

1. Python sorted list

List1 = ['8', '3', '7', '6', '5', '9']

print("returning a sorted list in ascending order: "),

print(sorted(List1)

print("returning a sorted list in descending order: "),

print(sorted(List1, reverse = True))

Output: The above code results in the following output.

returning a sorted list in ascending order: ['3', '5', '6', '7', '8',' 9']

returning a sorted list in descending order: ['9', '8', '7', '6', '5', '3']

We got a sorted list in ascending order as output in the first line because we didn’t give the reverse parameter as input. So, the function by default takes False as the default value and returns a sorted list in ascending order and we get a sorted list in descending order as output in the second line because this time we gave True as the reverse parameter in the input.

2. Sorting a Tuple

Tuple1 = ('e', 'y', 's', 'b', 'd', 'f')

print("returning a sorted tuple in ascending order: "),

print(sorted(Tuple1)

print("returning a sorted tuple in descending order: "),

print(sorted(Tuple1, reverse = True))

Output: The above code results in the following output.

returning a sorted list in ascending order: ['b', 'd', 'e', 'f', 's', 'y']

returning a sorted list in descending order: ['y', 's', 'f', 'e', 'd', 'b']

We got a sorted tuple in ascending order as output in the first line because we didn’t give the reverse parameter as input. So, the function by default takes False as the default value and returns a sorted tuple in ascending order and we get a sorted tuple in descending order as output in the second line because this time we gave True as the reverse parameter in the input.

3. Sorting a String

str = "Python"

print("returning a sorted string in ascending order: "),

print(sorted(str))

print("returning a sorted string in descending order: "),

print(sorted(str, reverse = True)

Output: The above code results in the following output.

returning a sorted string in ascending order: ['h','n','o','p','t','y']

returning a sorted string in descending order: ['y','t','p','o','n','h']

We got a sorted string in ascending order as output in the first line because we didn’t give the reverse parameter as input. So, the function by default takes False as the default value and returns a sorted string in ascending order and we get a sorted string in descending order as output in the second line because this time we gave True as the reverse parameter in the input.

Example 2: python sorted descending using key parameter in sorted function python

The optional parameter “key” is used to give a function as input, which transforms each element before sorting. The function takes in one value and returns one value, which is then sorted instead of the original value.

For instance, if a list of strings is sorted using the Python sorted() function, it gets sorted alphabetically. But if we give the len function as the key to the sorted() function, then the strings are passed to len, and the length values returned by the len function will be sorted instead of sorting the strings alphabetically or numerically. List = ["1111", "333", "4", "22"]

print ("Normal sort :", sorted(List))

print ("Sorting with length :", sorted(List, key = len))

print ("Sort with length in descending order :", sorted(List, key = len, reverse = True))

Output: The above code results in the following output.

Normal sort : ['1111', '22', '333', '4']

Sorting with length : ['4','22','333','1111']

Sort with length in descending order: ['111','333','22','4']

In the last line of output, we can see that the list was sorted based on the lengths of the strings and in descending order as we have also given the reverse parameter value as True.

Example 3: Sort the list using sorted() specifying the key function

def func(a):

return a % 7

List = [15, 9, 11, 7]

print ("Normal sort :", sorted(List))

print ("Sorted with key:", sorted(List, key = func))

Output:

The above code results in the following output.

Normal sort : ['7', '9', '11', '15'] Sorted with key: ['7', '15','9','11']

In the second line, we got 15 printed before 9 because we have given the function which returns the remainder of the number divided by 7 and then the returned value is sorted. So 15 ob being divided by 7 leaves a remainder 1 which is less than the remainder of 9 divided by 7 which is 2. So, this is how we can use the key parameter to send in a function and sort the values using that function.

Example 4: Sorting with multiple keys

Now, let us learn the know-how the sorted() function works with multiple keys. In Python, to use the sorted() function with two key values you need to create a lambda function first which takes an element as a parameter and then returns a 2-tuple of mapped values.

list = ["aaa", "cc", "bb"]

new_list = sorted(list, key=lambda x: (len(x), x))

#Sorts by length then alphabetically

print(new_list)

Output: The above code results in the following output.

Here, since we have used multiple keys where we have given the len function as the first value and then the original value as the second value, the sorted() function has sorted the values first based on their lengths and then sorted them alphabetically.

FAQs on Python sorted

Now, to give you a quick bride about the working of sorted() function, we have answered some frequently asked questions in the below section, which are:

Q1. What is sorted in Python?

A. In Python, sorted() is an in-built function that is used to sort a Sequence (tuple, string, list) or collection (set, dictionary, frozenset) and get a sorted list as output either in ascending or descending order based on the context of the problem.

Q2. Is sorted in-place Python?

A. In Python, there are two sort functions, of which one is sort() that sorts a list in-place and the second one is sorted() which sorts an iterable and returns a list as output.

Q3. How does Python sorted work?

A. Sorted() in Python works by taking in three parameters of which two are optional.

Syntax: Sorted(iterable, key, reverse)

Parameters:

• Iterable (required parameter)
• Key (optional parameter)
• Reverse (optional parameter)

The key parameter is used to take in a function as input which takes in the values of the iterable and returns new values based on which the new sorted list is created and the reverse parameter is used to instruct the sorted() function either to sort the iterable in ascending or descending order and then finally returns a sorted list as output.

Q4. Is a Python dictionary sorted?

A. Yes, a dictionary(collection of items in which the items are stored as key-value pairs) in Python can be sorted based on the order of item insertion. But, it was not possible in the earlier versions.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.  Ashhar Firdausi
IIT Roorkee
Biology  Dr. Nazma Shaik
VTU
Chemistry  Gaurav Tiwari
APJAKTU
Physics
Get Started 