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.
The syntax of the sorted()
method is as follows.
sorted(iterable, key=func, reverse=boolVar)
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.The return value of the sorted()
method is the object in sorted form.
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 alphabetsalpha = ["b", "g", "a", "f", "d"]sortedAlpha = sorted(alpha)print(sortedAlpha)# sorting a set of integersnum = (1,10,33,2,67,24,7,4)sortedNum = sorted(num)print(sortedNum)# sorting with reverse argument i.e, in descending ordersortedNumD = sorted(num, reverse=True)print(sortedNumD)# sorting with a key function lengthstring = ["abc", "a", "afteg", "lkimty", "av", "kmtn"]sortedNumKey = sorted(string, key=len)print(sortedNumKey)