Python sorted() Function

Sorts the items of an iterable

Usage

The sorted() method sorts the items of any iterable

You can optionally specify parameters for sort customization like sorting order and sorting criteria.

Syntax

sorted(iterable,key,reverse)

The method has two optional arguments, which must be specified as keyword arguments.

Python sorted() function parameters
ParameterConditionDescription
iterableRequiredAny iterable (list, tuple, dictionary, set etc.) to sort.
keyOptionalA function to specify the sorting criteria.
Default value is None.
reverseOptionalSettting it to True sorts the list in reverse order.
Default value is False.

Return Value

The method returns a new sorted list from the items in iterable.

Sort Iterables

sorted() function accepts any iterable like list, tuple, dictionary, set, string etc.

Example: Sort a list of strings and numbers

# strings are sorted alphabetically
L = ['red', 'green', 'blue', 'orange']
x = sorted(L)
print(x)    # ['blue', 'green', 'orange', 'red']
# numbers are sorted numerically
L = [42, 99, 1, 12]
x = sorted(L)
print(x)    # [1, 12, 42, 99]

If you want to sort the list in-place, use built-in sort() method.

sort() is actually faster than sorted() as it doesn’t need to create a new list.

Example: Sort a tuple

L = ('cc', 'aa', 'dd', 'bb')
x = sorted(L)
print(x)    # ['aa', 'bb', 'cc', 'dd']

sorted() function sorts a dictionary by keys, by default.

Example: Sort a dictionary by keys

D = {'Bob':30, 'Sam':25, 'Max':35, 'Tom':20}
x = sorted(D)
print(x)	# ['Bob', 'Max', 'Sam', 'Tom']

To sort a dictionary by values use the sorted() function along with the values() method.

Example: Sort a dictionary by values

D = {'Bob':30, 'Sam':25, 'Max':35, 'Tom':20}
x = sorted(D.values())
print(x)    # [20, 25, 30, 35]

Sort in Reverse Order

You can also sort an iterable in reverse order by setting reverse to true.

Example: Sort a list in reverse order (Descending)

L = ['cc', 'aa', 'dd', 'bb']
x = sorted(L, reverse=True)
print(x)    # ['dd', 'cc', 'bb', 'aa']

Sort with Key

Use key parameter for more complex custom sorting.

A key parameter specifies a function to be executed on each list item before making comparisons.

For example, with a list of strings, specifying key=len (the built-in len() function) sorts the strings by length, from shortest to longest.

Example: Sort a list by the length of the items

L = ['orange', 'red', 'green', 'blue']
x = sorted(L, key=len)
print(x)       # ['red', 'blue', 'green', 'orange']

Sort with Custom Function

You can also pass in your own custom function as the key function.

Example: Sort a list of tuples based on the age of students

def myFunc(e):
  return e[1]	# return age

L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=myFunc)
print(x)	# [('Max', 25), ('Bob', 30), ('Sam', 35)]

A key function takes a single argument and returns a key to use for sorting.

Sort with lambda

A key function may also be created with the lambda expression.

It allows us to in-line function definition.

Example: Sort a list of tuples based on the age of students

L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=lambda student: student[1])
print(x)	# [('Max', 25), ('Bob', 30), ('Sam', 35)]

Sort with Operator Module Functions

To access items of an iterable, Python provides convenience functions like itemgetter() and attrgetter() from operator module.

Example: Sort a list of tuples with itemgetter

from operator import itemgetter

L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=itemgetter(1))
print(x)	# [('Max', 25), ('Bob', 30), ('Sam', 35)]

Multiple Level Sorting

The operator module functions allow multiple levels of sorting as well.

Example: Sort a list of tuples by grade then by age

from operator import itemgetter

L = [('Bob', 'B', 30),
	('Sam', 'A', 35),
    ('Max', 'B', 25),
    ('Tom', 'A', 20),
    ('Ron', 'A', 40),
    ('Ben', 'B', 15)]
x = sorted(L, key=itemgetter(1,2))
print(x)

Sorted Output:

[('Tom', 'A', 20),
 ('Sam', 'A', 35),
 ('Ron', 'A', 40),
 ('Ben', 'B', 15),
 ('Max', 'B', 25),
 ('Bob', 'B', 30)]

Sort Custom Objects

Let’s create a list of custom objects.

Prerequisite:

# Custom class
class Student:
	def __init__(self, name, grade, age):
		self.name = name
		self.grade = grade
		self.age = age
	def __repr__(self):
		return repr((self.name, self.grade, self.age))

# a list of custom objects
L = [Student('Bob', 'B', 30),
	Student('Sam', 'A', 35),
	Student('Max', 'B', 25)]

Here are some techniques to sort a list of custom objects.

Example: Sort a list of custom objects with lambda

x = sorted(L, key=lambda student: student.age)
print(x)
# [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]

Example: Sort a list of custom objects with attrgetter

from operator import attrgetter

x = sorted(L, key=attrgetter('age'))
print(x)
# [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]

Example: Custom Objects – Multiple Level Sorting

x = sorted(L, key=attrgetter('grade', 'age'))
print(x)
# [('Sam', 'A', 35), ('Max', 'B', 25), ('Bob', 'B', 30)]