Python sorted() Function
The sorted()
method sorts the items of any iterable.
-
The iterable can be any sequence we want to sort, such as list, tuple, string, dictionary, set, frozen set, etc.
-
Strings are sorted alphabetically
-
Numbers are sorted numerically
You can not sort a list that contains BOTH string values AND numeric values.
Syntax
sorted(iterable, key, reverse)
sorted() Parameters
Python sorted()
function parameters:
Parameter | Condition | Description |
---|---|---|
iterable | Required | Any iterable (list, tuple, string, dictionary, set etc.) to sort. |
key | Optional | A function to specify the sorting criteria. Default value is None . |
reverse | Optional | Setting it to True sorts the list in reverse order. Default value is False . |
sorted() Return Value
Python sorted()
function returns a new sorted list from the items in iterable.
Examples
Example 1: Sort a String
sorted()
function sorts strings alphabetically:
my_string = "Tutorial Reference!"
sorted_string = sorted(my_string)
print(sorted_string) # Output: [' ', '!', 'R', 'T', 'a', 'c', 'e', 'e', 'e', 'e', 'f', 'i', 'l', 'n', 'o', 'r', 'r', 't', 'u']
output
[' ', '!', 'R', 'T', 'a', 'c', 'e', 'e', 'e', 'e', 'f', 'i', 'l', 'n', 'o', 'r', 'r', 't', 'u']
Example 2: Sort a List
sorted()
function sorts numbers numerically:
my_list = [123, 99, 23, 25, 1]
x = sorted(my_list)
print(x) # Output: [1, 23, 25, 99, 123]
output
[1, 23, 25, 99, 123]
If you want to sort the list in-place, use built-in sort()
method of lists.
Example 3: Sort a Tuple
numbers = (4, 25, 23, 6, 8, 15)
print(sorted(numbers)) # Output: [1, 2, 4, 6, 8, 15]
output
[4, 6, 8, 15, 23, 25]
Example 4: Sort a Dictionary by Keys
sorted()
function sorts a dictionary by keys, by default.
my_dict = {1: 'one', 2: 'two', 3: 'three'}
print(sorted(my_dict)) # Output: [1, 2, 3]
output
[1, 2, 3]
Example 5: Sort a Dictionary by Values
To sort a dictionary by values use the sorted()
function along with
the values()
method.
my_dict = {1: 'one', 2: 'two', 3: 'three'}
x = sorted(my_dict.values())
print(x) # Output: ['one', 'three', 'two']
output
['one', 'three', 'two']
Example 6: Sort in reverse order
You can also sort an iterable
in reverse order by setting reverse
parameter to True
.
numbers = [4, 25, 23, 6, 8, 15]
x = sorted(numbers, reverse=True)
print(x) # Output: [25, 23, 15, 8, 6, 4]
output
[25, 23, 15, 8, 6, 4]
Example 7: Sort with Key parameter
You can 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.
my_list = ['orange', 'red', 'green', 'blue']
x = sorted(my_list, key=len)
print(x) # Output: ['red', 'blue', 'green', 'orange']
output
['red', 'blue', 'green', 'orange']
Example 8: Sort using Custom Function
You can also pass to the sorted()
function your own custom function as key
function. A key
function should take a
single argument and return a key to use for sorting.
For example, sort a list of students (as list of tuple) by age (second element of the tuple):
def sortByAge(e):
return e[1] # return age
students = [('Tom', 30),('Anna', 23), ('Dave', 25)]
x = sorted(students, key=sortByAge)
print(x) # Output: [('Anna', 23), ('Dave', 25), ('Tom', 30)]
output
[('Anna', 23), ('Dave', 25), ('Tom', 30)]
Example 9: Sort using Lambda
A key function may also be created with the lambda expression. It allows us to in-line function definition.
For example, sort a list of students (as list of tuple) by age (second element of the tuple):
students = [('Tom', 30),('Anna', 23), ('Dave', 25)]
x = sorted(students, key=lambda student: student[1])
print(x) # Output: [('Anna', 23), ('Dave', 25), ('Tom', 30)]
output
[('Anna', 23), ('Dave', 25), ('Tom', 30)]
Example 10: Sort using Operator Module Functions
To access items of an iterable, Python provides convenience functions
like itemgetter()
and attrgetter()
from operator
module.
For example, sort a list of students (as list of tuple) by age (second element of the tuple):
from operator import itemgetter
students = [('Tom', 30),('Anna', 23), ('Dave', 25)]
x = sorted(students, key=itemgetter(1))
print(x) # Output: [('Anna', 23), ('Dave', 25), ('Tom', 30)]
output
[('Anna', 23), ('Dave', 25), ('Tom', 30)]
Example 11: Multiple Level Sorting (nested sorting)
The operator module functions allow multiple levels of sorting as well.
For example, sort students by grade and then by age:
from operator import itemgetter
students = [('Bob', 'B', 30),
('Anna', 'A', 23),
('Max', 'B', 18),
('Tom', 'A', 29),
('Dave', 'A', 25),
('Ryan', 'B', 15)]
x = sorted(students, key=itemgetter(1,2))
print(x) # [('Anna', 'A', 23), ('Dave', 'A', 25), ('Tom', 'A', 29), ('Ryan', 'B', 15), ('Max', 'B', 18), ('Bob', 'B', 30)]
output
[('Anna', 'A', 23), ('Dave', 'A', 25), ('Tom', 'A', 29), ('Ryan', 'B', 15), ('Max', 'B', 18), ('Bob', 'B', 30)]
Example 12: Sort Custom Objects
Consider a list of custom objects:
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
my_list = [Student('Bob', 'B', 30),
Student('Dave', 'A', 25),
Student('Anna', 'B', 23)]
Then, there are different techniques to sort my_list
list of custom objects:
# with lambda
result_lambda = sorted(my_list, key=lambda student: student.age)
print(result_lambda) # [('Anna', 'B', 23), ('Dave', 'A', 25), ('Bob', 'B', 30)]
output
[('Anna', 'B', 23), ('Dave', 'A', 25), ('Bob', 'B', 30)]
# with attrgetter
from operator import attrgetter
result_attrgetter = sorted(my_list, key=attrgetter('age'))
print(result_attrgetter) # [('Anna', 'B', 23), ('Dave', 'A', 25), ('Bob', 'B', 30)]
output
[('Anna', 'B', 23), ('Dave', 'A', 25), ('Bob', 'B', 30)]
# Multiple Level Sorting with custom objects
from operator import attrgetter
# Sort by grade and then by age
result_multi_level = sorted(my_list, key=attrgetter('grade', 'age'))
print(result_multi_level) # [('Dave', 'A', 25), ('Anna', 'B', 23), ('Bob', 'B', 30)]
output
[('Dave', 'A', 25), ('Anna', 'B', 23), ('Bob', 'B', 30)]
Example 13: Sort a List of Tuples by a Specific Element
For example, let's sort a list of tuples based on the first element of each tuple.
A lambda function is passed as the key
argument to sorted()
function, specifying that the sorting should be done
based on the first element of each tuple.
my_tuples = [(4, 'banana'), (1, 'apple'), (3, 'cherry'), (2, 'orange')]
sorted_tuples = sorted(my_tuples, key=lambda x: x[0])
print(sorted_tuples) # Output: [(1, 'apple'), (2, 'orange'), (3, 'cherry'), (4, 'banana')]
output
[(1, 'apple'), (2, 'orange'), (3, 'cherry'), (4, 'banana')]
Example 14: Sort a List of Dictionaries by a Specific Key
For example, let's sort a list of dictionaries based on the value of a specific key. In this case we sort based on
the age
key of each dictionary.
my_dicts = [{'name': 'Tom', 'age': 26}, {'name': 'Dave', 'age': 25}, {'name': 'Anna', 'age': 23}]
sorted_dicts = sorted(my_dicts, key=lambda x: x['age'])
print(sorted_dicts) # Output: [{'name': 'Anna', 'age': 23}, {'name': 'Dave', 'age': 25}, {'name': 'Tom', 'age': 26}]
output
[{'name': 'Anna', 'age': 23}, {'name': 'Dave', 'age': 25}, {'name': 'Tom', 'age': 26}]