Python sorted() function

Filed Under: Python

Python sorted() function returns a sorted list from the items in the iterable.

Python sorted() function

Python sorted() function syntax is:

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

There are two optional arguments – key and reverse – which must be specified as keyword arguments.

  • iterable: elements from the iterable will be sorted. If key is not specified then natural sorting is used for the elements.
  • key: specifies a function of one argument that is used to extract a comparison key from each list element.
  • reverse: optional boolean argument. If specified as True then elements are sorted in reverse order.

Python sorted() string

String is iterable in Python, let’s see an example of using sorted() function with string argument.

s = sorted('djgicnem')

Output: ['c', 'd', 'e', 'g', 'i', 'j', 'm', 'n']

Python sorted() reverse

Let’s see the sorted list when reversed is passed as True.

s = sorted('azbyx', reverse=True)

Output: ['z', 'y', 'x', 'b', 'a']

Python sorted() tuple

s = sorted((1, 3, 2, -1, -2))

s = sorted((1, 3, 2, -1, -2), reverse=True)


[-2, -1, 1, 2, 3]
[3, 2, 1, -1, -2]

Python sorted() key

Let’s say we want to sort a sequence of numbers based on their absolute value, we don’t care about their being positive or negative. We can achieve this by passing key=abs to sorted() function. Note that abs() is the built-in function that returns the absolute value of the number.

s = sorted((1, 3, 2, -1, -2), key=abs)

Output: [1, -1, 2, -2, 3]

Python sort list

Let’s see some examples of using sorted() function with list.

s = sorted(['a', '1', 'z'])

s = sorted(['a', '1b', 'zzz'])

s = sorted(['a', '1b', 'zzz'], key=len)

s = sorted(['a', '1b', 'zzz'], key=len, reverse=True)


['1', 'a', 'z']
['1b', 'a', 'zzz']
['a', '1b', 'zzz']
['zzz', '1b', 'a']

sorted() vs list.sort()

  • sorted() function is more versatile because it works with any iterable argument.
  • Python sorted() function builds a new sorted list from an iterable whereas list.sort() modifies the list in-place.

sorted() with iterable of different element types

Let’s see what happens when we try to use sorted() function with iterable having different element types.

s = sorted(['a', 1, 'x', -3])


TypeError: '<' not supported between instances of 'int' and 'str'

python sorted function

sorted() with custom objects

We can use sorted() function to sort a sequence of custom object based on different types of criteria.

Let’s say we have an Employee class defined as:

class Employee:
    id = 0
    salary = 0
    age = 0
    name = ''

    def __init__(self, i, s, a, n): = i
        self.salary = s
        self.age = a = n

    def __str__(self):
        return 'E[id=%s, salary=%s, age=%s, name=%s]' % (, self.salary, self.age,

Now we have a list of employee objects as:

e1 = Employee(1, 100, 30, 'Amit')
e2 = Employee(2, 200, 20, 'Lisa')
e3 = Employee(3, 150, 25, 'David')
emp_list = [e1, e2, e3]

Sort list of employees based on id

def get_emp_id(emp):

emp_sorted_by_id = sorted(emp_list, key=get_emp_id)
for e in emp_sorted_by_id:


E[id=1, salary=100, age=30, name=Amit]
E[id=2, salary=200, age=20, name=Lisa]
E[id=3, salary=150, age=25, name=David]

Sort list of employees based on age

def get_emp_age(emp):
    return emp.age

emp_sorted_by_age = sorted(emp_list, key=get_emp_age)
for e in emp_sorted_by_age:


E[id=2, salary=200, age=20, name=Lisa]
E[id=3, salary=150, age=25, name=David]
E[id=1, salary=100, age=30, name=Amit]


Python sorted() function is guaranteed to be stable. It’s very powerful and allows us to sort a sequence of elements based on different keys.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation


  1. kashish says:

    how to sort using selection sort a program based on employees name,id and salary, given we have to make a class employee and define all the 3 in it

  2. rchung says:

    Hi I’m building a list and like to put in print, sort and title together in one command line. How to achieve that?

    print(“The New Shopping List: “, sorted(shopping_list), str(shopping_list).title())

    Thanks in advance!

  3. SARATH BABU says:

    Consider a case were ids are the same in the last example. How do I include string as well?

  4. Reginold Kolenchery says:

    How to sort based on two values?

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content