What is sorted() in Python?

The sorted() method in Python returns a sorted version of an iterable object. If the object contains alphabets instead of numbers, sorted() sorts them alphabetically.

Syntax

The syntax of the sorted() method is as follows.

sorted(iterable, key=func, reverse=boolVar)

Parameters

The sorted() function takes one mandatory and two optional parameters:

  • iterable (mandatory): the object that needs to be sorted.
  • key (optional): the function according to which sorting occurs. If this argument is not specified, it is None by default.
  • reverse (optional): a Boolean that tells whether to sort the object in ascending or descending order. The default is False, which specifies ascending sorting.

Return value

The return value of the sorted() method is the object in sorted form.

Code

In the code below, the sorted() function sorts the alphabetical and numerical iterable objects. Then, upon specifying the reverse argument as True, the function sorts the object in descending order.

In the final example, the key function is specified, which tells the sorted() method to sort the list on the basis of string length.

# sorting a list of alphabets
alpha = ["b", "g", "a", "f", "d"]
sortedAlpha = sorted(alpha)
print(sortedAlpha)
# sorting a set of integers
num = (1,10,33,2,67,24,7,4)
sortedNum = sorted(num)
print(sortedNum)
# sorting with reverse argument i.e, in descending order
sortedNumD = sorted(num, reverse=True)
print(sortedNumD)
# sorting with a key function length
string = ["abc", "a", "afteg", "lkimty", "av", "kmtn"]
sortedNumKey = sorted(string, key=len)
print(sortedNumKey)

Free Resources