In this article we will explore how to use the Python sorted() function.

Table of Contents



Introduction

Python sorted() function is a built-in function for sorting iterables.

It uses timsort as its sorting algorithm, which is derived from merge sort and insertion sort.


The syntax of the Python sorted() function is:

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

where:

  • iterable – can be any iterable Python object like string, tuple, list, set, dictionary, and others.
  • key – optional argument that allows to add a function (for example lambda function) as a key for sorting. Defaults to None.
  • reverse – optional argument that allows to reverse the iterable (to sort in descending order) if set to True. Defaults to False.

The sorted() function process is defined as:

sorted(iterable) -> sorted list

Basic sorting using sorted()

There are many applications of the sorted() function, so let’s take at a few basic examples.


Sort a list of numbers in ascending order

The simplest example is to sort a list of numbers in ascending order:


#Create a list of numbers
nums = [3, 1, 9, 7, 5]

#Sort the list of numbers
s_nums = sorted(nums)

#Print sorted list
print(s_nums)

and you should get:

[1, 3, 5, 7, 9]

Sort a list of numbers in descending order

Similar to the previous example, we will be sorting a list of numbers, but now in descending order:


#Create a list of numbers
nums = [3, 1, 9, 7, 5]

#Sort the list of numbers
s_nums = sorted(nums, reverse=True)

#Print sorted list
print(s_nums)

and you should get:

[9, 7, 5, 3, 1]

Sort a list of strings

Python sorted() function can also sort lists with string elements in it.

The procedure with sorting numbers is very simple and intuitive, and it can be extended to sorting strings.

Python sorted() function sorts strings based on the first character of each string (for example, ‘apple’ comes before ‘orange’ since ‘a’ is before ‘o’ in the alphabet).

Let’s take a look at an example:


#Create a list of strings
fruit = ['banana', 'pineapple', 'orange', 'apple']

#Sort the list of strings
s_fruit = sorted(fruit)

#Print sorted list
print(s_fruit)

and you should get:

['apple', 'banana', 'orange', 'pineapple']

As you can see, the list of strings has been sorted in alphabetical (ascending) order based on the first character of the string.

You can also sort a list of strings in descending order by setting the optional reverse argument to True.


Note: you can extend the above functionality to other iterables, like tuples, sets, and others.


Using key function with sorted()

For more complex sorting tasks we can add the usage of key function in sorted() which will act as a key for sorting.

There are two ways of using a key function:


Using lambda function with sorted()

Let’s create some sample list with words:

['Python', 'programming', 'tutorial', 'code']

Now, in this example, we would like to sort the list based on the length of the elements, meaning that the words will be ordered from shortest to longest based on the number of characters.

As you can imagine, we will have to use the len() function to calculate the length of each element, and using a lambda function we can use it as a key function for sorting:


#Create a list of words
words = ['Python', 'programming', 'tutorial', 'code']

#Sort the list of words based on length of each word
s_words = sorted(words, key=lambda x: len(x))

#Print sorted list
print(s_words)

and you should get:

['code', 'Python', 'tutorial', 'programming']

Using custom function with sorted()

Let’s reuse the same list of words from the previous example:

['Python', 'programming', 'tutorial', 'code']

Now, we would like to perform the same sorting based on length of each element in the list, but using a custom function to calculate the length of each word.

We can define a simple function to calculate the length of a word, and pass it into sorted() as a key function:


#Create a list of words
words = ['Python', 'programming', 'tutorial', 'code']

#Define a function to calculate length of a word
def calc_len(word):
    len_w = len(word)
    return len_w

#Sort the list of words based on length of each word
s_words = sorted(words, key=calc_len)

#Print sorted list
print(s_words)

and you should get:

['code', 'Python', 'tutorial', 'programming']

which is the same result as when we used the len() with lambda function as a key function for sorted().


Sort custom objects using sorted()

The functionality of Python sorted() function can be extended to custom objects (as long as we are sorting iterables).

For example, let’s create a custom class Person with two attributes name and age:


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __repr__(self):
        return repr((self.name, self.age))

This class will create a list of tuples with information of each person:


#Create a list of tuples
persons = [
    Person('Mike', 20),
    Person('John', 35),
    Person('David', 23),
]

#Print list of tuples
print(persons)

and you should get:

[('Mike', 20), ('John', 35), ('David', 23)]

As you can see this is now a list of tuples, which is a Python iterable, and can be sorted using sorted() function.

In this example, we would like to sort the list based on age attribute of each person:


#Sort the list of tuples based on age attribute
s_persons = sorted(persons, key=lambda person: person.age)

#Print sorted list
print(s_persons)

and you should get:

[('Mike', 20), ('David', 23), ('John', 35)]

Conclusion

In this article we explored how to use Python sorted() function.

Now that you know the basic functionality, you can practice using it with other iterable data structures for more complex use cases.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Functions tutorials.