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.
Parameter | Condition | Description |
iterable | Required | Any iterable (list, tuple, dictionary, set etc.) to sort. |
key | Optional | A function to specify the sorting criteria. Default value is None. |
reverse | Optional | Settting 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.
# strings are sorted alphabetically
L = ['red', 'green', 'blue', 'orange']
x = sorted(L)
print(x)
# Prints ['blue', 'green', 'orange', 'red']
# numbers are sorted numerically
L = [42, 99, 1, 12]
x = sorted(L)
print(x)
# Prints [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.
# Sort a tuple
L = ('cc', 'aa', 'dd', 'bb')
x = sorted(L)
print(x)
# Prints ['aa', 'bb', 'cc', 'dd']
sorted()
function sorts a dictionary by keys, by default.
D = {'Bob':30, 'Sam':25, 'Max':35, 'Tom':20}
x = sorted(D)
print(x)
# Prints ['Bob', 'Max', 'Sam', 'Tom']
To sort a dictionary by values use the sorted()
function along with the values() method.
D = {'Bob':30, 'Sam':25, 'Max':35, 'Tom':20}
x = sorted(D.values())
print(x)
# Prints [20, 25, 30, 35]
Sort in Reverse Order
You can also sort an iterable in reverse order by setting reverse to true.
L = ['cc', 'aa', 'dd', 'bb']
x = sorted(L, reverse=True)
print(x)
# Prints ['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.
L = ['orange', 'red', 'green', 'blue']
x = sorted(L, key=len)
print(x)
# Prints ['red', 'blue', 'green', 'orange']
Sort with Custom Function
You can also pass in your own custom function as the key function. A key function should take a single argument and return a key to use for sorting.
# Sort by 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)
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
Sort with lambda
A key function may also be created with the lambda expression. It allows us to in-line function definition.
# Sort by the age of students
L = [('Sam', 35),
('Max', 25),
('Bob', 30)]
x = sorted(L, key=lambda student: student[1])
print(x)
# Prints [('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.
# Sort by the age of students
from operator import itemgetter
L = [('Sam', 35),
('Max', 25),
('Bob', 30)]
x = sorted(L, key=itemgetter(1))
print(x)
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
Multiple Level Sorting
The operator module functions allow multiple levels of sorting as well.
# Sort 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)
# Prints [('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.
# 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.
# with lambda
x = sorted(L, key=lambda student: student.age)
print(x)
# [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]
# with attrgetter
from operator import attrgetter
x = sorted(L, key=attrgetter('age'))
print(x)
# [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]
# Custom Objects - Multiple Level Sorting
# Sort by grade then by age
x = sorted(L, key=attrgetter('grade', 'age'))
print(x)
# [('Sam', 'A', 35), ('Max', 'B', 25), ('Bob', 'B', 30)]