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')
print(s)

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)
print(s)

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

Python sorted() tuple


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

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

Output:


[-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)
print(s)

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'])
print(s)

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

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

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

Output:


['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])

Output:


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):
        self.id = i
        self.salary = s
        self.age = a
        self.name = n

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

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):
    return emp.id


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

Output:


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:
    print(e)

Output:


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]

Summary

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

Comments

  1. Reginold Kolenchery says:

    How to sort based on two values?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages