Python sorted()

The sorted() method returns a sorted list from the given iterable.

The sorted() method sorts the elements of a given iterable in a specific order - Ascending or Descending.

The syntax of sorted() method is:

sorted(iterable[, key][, reverse])

sorted() Parameters

sorted() takes two three parameters:

  • iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator 
  • reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order)
  • key (Optional) - function that serves as a key for the sort comparison

Return value from sorted()

sorted() method returns a sorted list from the given iterable.


Example 1: Sort a given sequence: string, list and tuple

# vowels list
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList))

# string 
pyString = 'Python'
print(sorted(pyString))

# vowels tuple
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))

When you run the program, the output will be:

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

Note: A list also has sort() method which performs the same way as sorted(). Only difference being, sort() method doesn't return any value and changes the original list itself.


Example 2: Sort a given collection in descending order: set, dictionary and frozen set

sorted() method accepts a reverse parameter as an optional argument.

Setting reverse=True sorts the iterable in the descending order.

# set
pySet = {'e', 'a', 'u', 'o', 'i'}
print(sorted(pySet, reverse=True))

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

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

When you run the program, the output will be:

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

How to sort using your own function with key parameter?

If you want your own implementation for sorting, sorted() also accepts a key function as an optional parameter.

Based on the results of the key function, you can sort the given iterable.

sorted(iterable, key=len)

Here, len is the Python's in-built function to count the length of an element.

The list is sorted based on the length of its each element, from lowest count to highest.

Example 3: Sort the list using sorted() having a key function

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

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

# sort list with key
sortedList = sorted(random, key=takeSecond)

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

When you run the program, the output will be:

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