Tutorial Study Image

Python sorted()

The built-in function sorted()  returns a sorted list of given iterable. The sorting may be in an ascending or descending order. If the iterable is a string it sorts alphabetically if it is a number it sorts numerically. In the case of iterable which have both string and numbers that cannot sort.

sorted(iterable, key=None, reverse=False) #where iterable may be string, tuple, list,set, dictionary frozen set) 

sorted() Parameters:

Takes three parameters. Based on the returned value of the key function,we can sort the given iterable as below

sorted(iterable, key=len)

Parameter Description Required / Optional
iterable A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator. Required
reverse If True, the sorted list is reversed (or sorted in descending order). Defaults to False if not provided. Optional
key A function that serves as a key for the sort comparison. Defaults to None. Optional

sorted() Return Value

This sorted() method is similar to sort(), the difference is that sort() doesn't return any value.

Input Return Value
 Iterable sorted list

Examples of sorted() method in Python

Example 1: How to sort string, list, and tuple

# vowels list pyth 'a', 'u', 'o', 'i']

# string pyth

# vowels tuple pyth 'a', 'u', 'o', 'i')


['a', 'e', 'i', 'o', 'u']
['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']

Example 2:How to sort in descending order

# set pyth 'a', 'u', 'o', 'i'}
print(sorted(python_set, reverse=True))

# dictionary pyth 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print(sorted(python_dict, reverse=True))

# frozen set
frozen_set = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(frozen_set, reverse=True))


['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']

Example 3: How to sort the list using sorted() having a key function

# take the second element for sort
def take_second(elem):
    return elem[1]

# random list
randomnum = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key
sorted_keylist = sorted(randomnum, key=take_second)

# print list
print('Sorted list:', sorted_keylist)


Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

Example 4: How to sort with multiple keys

# Nested list of student's info in a Science Olympiad
# List elements: (Student's Name, Marks out of 100, Age)

student_list = [
    ('Alison', 50, 18),
    ('Terence', 75, 12),
    ('David', 75, 20),
    ('Jimmy', 90, 22),
    ('John', 45, 12)


[('Jimmy', 90, 22), ('Terence', 75, 12), ('David', 75, 20), ('Alison', 50, 18), ('John', 45, 12)]