Python sorted() function

Updated on Jan 07, 2020


The sorted() built-in function allows us to sort the data. It accepts an iterable and returns a sorted list containing the items from the iterable. By default, it sorts in ascending order.

The syntax of sorted() function is as follows:

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

Parameter Description
iterable (required) Iterable to sort like string, list, dictionary, tuple etc.
key , (optional) It refers to the single argument function to customize the sort order. The function is applied to each item on the iterable. By default, this argument is set to None.
reverse (optional)  A boolean flag to reverse the sorting order. It defaults to False.

If the items in the iterable is a string, they will be sorted in alphabetical order. On the other hand, if they are numbers, they will be sorted in numerical order.

Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
>>> 
>>> fruits = ['lime', 'blueberry', 'plum', 'avocado']
>>> 
>>> sorted(fruits) # default sorting, in ascending order
['avocado', 'blueberry', 'lime', 'plum']
>>> 
>>> 
>>> sorted(fruits, reverse=True) # reverse the sorting
['plum', 'lime', 'blueberry', 'avocado']
>>> 
>>> 
>>> ages = [45, 11, 30, 20, 55]
>>> 
>>> sorted(ages)
[11, 20, 30, 45, 55]
>>> 
>>> sorted(ages, reverse=True)
[55, 45, 30, 20, 11]
>>>

Try it out:

fruits = ['lime', 'blueberry', 'plum', 'avocado']
 
print(sorted(fruits)) # default sorting, in ascending order
print(sorted(fruits, reverse=True)) # reverse the sorting

ages = [45, 11, 30, 20, 55]

print(sorted(ages))
print(sorted(ages, reverse=True))


Note that the sorted() returns a new list containing items from the iterable. It doesn't change the original iterable in the process.

1
2
3
4
5
6
7
8
>>> 
>>> fruits # fruit list is same as before
['lime', 'blueberry', 'plum', 'avocado']
>>> 
>>>
>>> ages # ages list is same as before
[45, 11, 30, 20, 55]
>>>

Try it out:

fruits = ['lime', 'blueberry', 'plum', 'avocado']
ages = [45, 11, 30, 20, 55]
 
print(sorted(fruits)) # default sorting, in ascending order
print(sorted(fruits, reverse=True)) # reverse the sorting

print(fruits)
print(ages)


Here are some other examples showing how sorted() works with other Python types.

sorted() with string #


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> 
>>> name = "Alfred Hajos"
>>> 
>>> sorted(name)
[' ', 'A', 'H', 'a', 'd', 'e', 'f', 'j', 'l', 'o', 'r', 's']
>>> 
>>> 
>>> sorted(name, reverse=True)
['s', 'r', 'o', 'l', 'j', 'f', 'e', 'd', 'a', 'H', 'A', ' ']
>>>

Try it out:

name = "Alfred Hajos"

print(sorted(name))
print(sorted(name, reverse=True))


Notice that in the result of the first sorted() call A come before a. This is because the ASCII value of A is 65 and that of a is 97. For the same reason space character (' '), ASCII value of 32 comes before A.

sorted() with tuple #


1
2
3
4
5
6
7
8
9
>>> 
>>> t = ( 'ff', 'xx', 'gg', 'aa')
>>> 
>>> sorted(t)
['aa', 'ff', 'gg', 'xx']
>>> 
>>> sorted(t, reverse=True)
['xx', 'gg', 'ff', 'aa']
>>>

Try it out:

t = ( 'ff', 'xx', 'gg', 'aa')

print(sorted(t))
print(sorted(t, reverse=True))


sorted() with dictionary #


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> 
>>> d = {'name': 'John', 'age': 25, 'designation': 'manager'}
>>> 
>>>
>>> sorted(d)
['age', 'designation', 'name']
>>> 
>>> sorted(d, reverse=True)
['name', 'designation', 'age']
>>> 
>>> 
>>> for k in sorted(d):
...     print(k, d[k])
... 
age 25
designation manager
name John
>>> 
>>> 
>>> for k in sorted(d, reverse=True):
...     print(k, d[k])
... 
name John
designation manager
age 25
>>>
d = {'name': 'John', 'age': 25, 'designation': 'manager'}

print(sorted(d))
print(sorted(d, reverse=True))

for k in sorted(d):
    print(k, d[k])

print('-'*10)

for k in sorted(d, reverse=True):
    print(k, d[k])


Customizing the sort order using the key named argument. #


From the preceding section, we know that if we apply sorted() function on a list of strings, we will get a list of strings sorted in alphabetical order.

What if we want to sort by length of the string instead of its alphabetical order?

This is where the key named argument come into the play.

To sort by string length set the key named argument to len() function as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> 
>>> fruits
['lime', 'blueberry', 'plum', 'avocado']
>>> 
>>> sorted(fruits) # sort by alphabetical order
['avocado', 'blueberry', 'lime', 'plum']
>>> 
>>> sorted(fruits, key=len) # sort by string length
['lime', 'plum', 'avocado', 'blueberry']
>>> 
>>> sorted(fruits, key=len, reverse=True) # reverse sort order
['blueberry', 'avocado', 'lime', 'plum']
>>>

Try it out:

fruits = ['lime', 'blueberry', 'plum', 'avocado']

print(fruits)

print(sorted(fruits))

print(sorted(fruits, key=len))  # sort by string length

print(sorted(fruits, key=len, reverse=True)) # reverse sort order


At times you may want to make the sorting case-insensitive. We can easily achieve this by setting key named argument to str.lower function.

1
2
3
4
5
6
7
8
9
>>> 
>>> t = ( 'AA', 'aa', 'ZZ', 'cc', 'bb')
>>> 
>>> sorted(t)
['AA', 'ZZ', 'aa', 'bb', 'cc']
>>> 
>>> sorted(t, key=str.lower)
['AA', 'aa', 'bb', 'cc', 'ZZ']
>>>
t = ( 'AA', 'aa', 'ZZ', 'cc', 'bb')

print(sorted(t))
print(sorted(t, key=str.lower))


Here is another example which uses a custom function to sort a list of strings based on the number of vowels it contains.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> 
>>> fruits
['lime', 'blueberry', 'plum', 'avocado']
>>>
>>> 
>>> def count_vowel(s):
...     vowels = ('a', 'e', 'i', 'o', 'u')
...     count = 0
... 
...     for i in s:
...         if i in vowels:
...         count = count + 1
... 
...     return count
... 
>>>
>>>
>>> sorted(fruits)
['avocado', 'blueberry', 'lime', 'plum']
>>> 
>>> sorted(fruits, key=count_vowel)
['plum', 'lime', 'blueberry', 'avocado']
>>>

Try it out:

fruits = ['lime', 'blueberry', 'plum', 'avocado'] 

def count_vowel(s):
    vowels = ('a', 'e', 'i', 'o', 'u')
    count = 0
 
    for i in s:
        if i in vowels:
            count = count + 1
 
    return count


print(sorted(fruits))

print(sorted(fruits, key=count_vowel))


You can also use sorted() on user-defined objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> 
>>> class Employee:
...     def __init__(self, name, salary, age):
...         self.name = name
...         self.salary = salary
...         self.age = age
... 
...     def __repr__(self):
...         return self.__str__()
... 
...     def __str__(self):
...         return "{0}:{1}:{2}".format(self.name, self.salary, self.age)
... 
>>> 
>>> 
>>> e1 = Employee("Tom", 20000, 32)
>>> e2 = Employee("Jane", 50000, 36)
>>> e3 = Employee("Bob", 45000, 40)
>>> 
>>> 
>>> emp_list = [e2, e3, e1]
>>> 
>>> print(emp_list)
[Jane:50000:36, Bob:45000:40, Tom:20000:32]
>>>
class Employee:
    def __init__(self, name, salary, age):
        self.name = name
        self.salary = salary
        self.age = age
 
    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return "{0}:{1}:{2}".format(self.name, self.salary, self.age)

e1 = Employee("Tom", 20000, 32)
e2 = Employee("Jane", 50000, 36)
e3 = Employee("Bob", 45000, 40)

emp_list = [e2, e3, e1]
 
print(emp_list)

# print(sorted(emp_list))


If you now call sorted() on emp_list you will get an error like this:

1
2
3
4
5
6
>>> 
>>> sorted(emp_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: Employee() < Employee()
>>>

tip:

The above code will not raise any error in Python 2. Instead, it will sort the Employee objects based upon the id returned by the id() built-in function.

This happens because Python doesn't know how to compare Employee objects. We can tell Python how to compare object by implementing special methods like __lt__(), __gt__() and so on, in the Employee class.

Instead, of defining special methods, we can explicitly tell the sorted() function how to sort Employee objects using the key named argument.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> 
>>> sorted(emp_list, key=lambda x: x.name) # sort Employee objects by name
[Bob:45000:40, Jane:50000:36, Tom:20000:32]
>>> 
>>> 
>>> sorted(emp_list, key=lambda x: x.age) # sort Employee objects by age
[Tom:20000:32, Jane:50000:36, Bob:45000:40]
>>> 
>>>
>>> print(sorted(emp_list, key=lambda x: x.salary)) # sort Employee objects by salary
[Tom:20000:32, Bob:45000:40, Jane:50000:36]
>>>
class Employee:
    def __init__(self, name, salary, age):
        self.name = name
        self.salary = salary
        self.age = age
 
    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return "{0}:{1}:{2}".format(self.name, self.salary, self.age)

e1 = Employee("Tom", 20000, 32)
e2 = Employee("Jane", 50000, 36)
e3 = Employee("Bob", 45000, 40)

emp_list = [e2, e3, e1]

print(sorted(emp_list, key=lambda x: x.name)) # sort Employee objects by name

print(sorted(emp_list, key=lambda x: x.age)) # sort Employee objects by age

print(sorted(emp_list, key=lambda x: x.salary)) # sort Employee objects by salary



Other Tutorials (Sponsors)