Python sorted() Method

The sorted() method returns a sorted list from the specified iterables (string, list, tuple, set).

Syntax:

sorted(iterable, key, reverse)

Parameters:

  1. iterable: The iterable to be arranged in ascending or descending order.
  2. key: (Optional) A function that serves as a key for the sort comparison.
  3. reverse: (Optional) If true, sorts in descending order.

Return Value:

Returns a list object with sorted items.

The following example returns the sorted list of the elements of iterable.

Example: Convert List, Tuple, String to Sorted List
nums = [2,1,5,3,4]
asc_nums = sorted(nums)
dsc_nums = sorted(nums, reverse = True)
print("Ascending Numbers: ", asc_nums)
print("Descending Numbers: ", dsc_nums)

nums_tuple = (8,7,6,10,9)
asc_nums = sorted(nums_tuple)
dsc_nums = sorted(nums_tuple, reverse = True)
print("Ascending Numbers: ", asc_nums)
print("Descending Numbers: ", dsc_nums)

mystr = 'gcadbfe'
asc_str = sorted(mystr)
dsc_str = sorted(mystr, reverse = True)
print("Ascending String: ", asc_str)
print("Reversed String: ", dsc_str)
Output
Ascending Numbers: [1, 2, 3, 4, 5]
Descending Numbers: [5, 4, 3, 2, 1]
Ascending Numbers: [6, 7, 8, 9, 10]
Descending Numbers: [10, 9, 8, 7, 6] 
Ascending String: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
Reversed String: ['g', 'f', 'e', 'd', 'c', 'b', 'a']

Above, the sorted() method returns the list object from passed iterables list, tuple, and string. The reverse = True parameter sorts the iterable in the reverse order.

The sorted() method extract keys of the specified dictionary and returns sorted list, as shown below.

Example: Dictionary Sorting
numdict = {1:'One',3:'Three', 2:'Two'}
asc_nums = sorted(numdict)
dsc_nums = sorted(numdict, reverse=True)

print("Ascending List: ", asc_nums)
print("Descending List: ", dsc_nums)
Output
Ascending List: [1, 2, 3]
Ascending List: [3, 2, 1]

Sort using Custom Function as Key

The key parameter can be used to sort the iterable based on different functions.

Example: sorted()
numstr = ('One','Two','Three','Four')
asc_nums = sorted(numstr, key=len)
dsc_nums = sorted(numstr, key=len, reverse=True)

print("Ascending List: ", asc_nums)
print("Descending List: ", dsc_nums)
Output
Ascending List: ['Four', 'One', 'Three', 'Two']
Descending List: ['Two', 'Three', 'One', 'Four']

You can use set user-defined function or lambda function to the key parameter. For example, the following sorts the list of string by the last character of a string.

Example: sorted()
def getlastchar(s):
	return s[len(s)-1]
     
code = ('bb','cd', 'aa', 'zc')
asc_code = sorted(code, key=getlastchar) # using user-defined function
dsc_code = sorted(code, key=getlastchar, reverse=True)

print("Ascending Code: ", asc_code)
print("Descending Code: ", dsc_code)

print('----Using lambda function----')
asc_code = sorted(code, key=lambda s: s[len(s)-1]) # using lambda function
dsc_code = sorted(code, key=lambda s: s[len(s)-1], reverse=True)

print("Ascending Code: ", asc_code)
print("Descending Code: ", dsc_code)
Output
Ascending Code: ['aa', 'bb', 'zc', 'cd']
Descending Code: ['cd', 'zc', 'bb', 'aa']
----Using lambda function----
Ascending Code: ['aa', 'bb', 'zc', 'cd']
Descending Code: ['cd', 'zc', 'bb', 'aa']
Want to check how much you know Python?