ScanSkill

sorted

This sorted() function returns a sorted list from the iterable in a specified order.

Syntax

sorted(*iterable[, cmp[, key[, reverse]]]*)
sorted(iterable, key=none, reverse=false)

Here,

  • iterable: Required. Must be a sequence, an iterator, or some other object which supports iteration.
  • key: Optional. A function of one argument that is used to compare. Default is None (compare the elements directly)
  • reverse: Optional. Boolean value, if True, the sorted list is reversed. Default is False.

Examples

  • With string, list, tuple, and dictionary
>>> # with string
>>> string1 = "Cloufyfox"
>>> sorted(string1)
['C', 'f', 'f', 'l', 'o', 'o', 'u', 'x', 'y']

>>> # with list
>>> list1 = ['cloudyfox', 'technology', 'pvt.', 'Ltd.']
>>> sorted(list1)
['Ltd.', 'cloudyfox', 'pvt.', 'technology']

>>> # with tuple
>>> tuple1 = (3, 25, 48, 4, 29, 13, 20)
>>> sorted(tuple1)
[3, 4, 13, 20, 25, 29, 48]

>>> # with dict
>>> dict1 = {'x': 1, 'c': 2, 'u': 3, 'o': 4, 'c': 5, 'l':6, 'd':7, 'f':8, 'o':9}
>>> sorted(dict1)
['c', 'd', 'f', 'l', 'o', 'u', 'x']
  • In reverse order (reverse=True)
>>> # with string
>>> string1 = "Cloufyfox"
>>> sorted(string1, reverse=True)
['y', 'x', 'u', 'o', 'o', 'l', 'f', 'f', 'C']

>>> # with list
>>> list1 = ['cloudyfox', 'technology', 'pvt.', 'Ltd.']
>>> sorted(list1, reverse=True)
['technology', 'pvt.', 'cloudyfox', 'Ltd.']

>>> # with tuple
>>> tuple1 = (3, 25, 48, 4, 29, 13, 20)
>>> sorted(tuple1, reverse=True)
[48, 29, 25, 20, 13, 4, 3]

>>> # with dict
>>> dict1 = {'x': 1, 'c': 2, 'u': 3, 'o': 4, 'c': 5, 'l':6, 'd':7, 'f':8, 'o':9}
>>> sorted(dict1, reverse=True)
['x', 'u', 'o', 'l', 'f', 'd', 'c']
  • With key function (key parameter)
>>> # Funtion which take 3rd element to sort
>>> def take_third_element(element):
...     return element[2]
... 
>>> list2 = [(3,2,7), (6,4,5), (3,5,2), (2,2,2), (8,5,9)]
>>> sorted(list2, key=take_third_element)
[(3, 5, 2), (2, 2, 2), (6, 4, 5), (3, 2, 7), (8, 5, 9)]
>>> sorted(['A', 'b', 'C'], key=lambda x: x.lower())
['A', 'b', 'C']
>>> sorted(((3, ), (1, 2, 3), (1, 2)), key=lambda x: sum(x))
[(3,), (1, 2), (1, 2, 3)]