lst = [5, 2, 3, 1, 4]
sorted(lst)
sorted(lst, reverse=True)
lst.sort()
lst.sort(reverse=True)
lst.sort(key=len, reverse=True)
* "key" parameter to specify a function to be called on each list element prior to making comparisons.
Examples
=======
>>> lst = [5,2,3,1,4]
>>>
>>>
>>> lst
[5, 2, 3, 1, 4]
>>>
>>>
>>> sorted(lst)
[1, 2, 3, 4, 5]
>>>
>>>
>>> res = sorted(lst)
>>>
>>>
>>> res
[1, 2, 3, 4, 5]
>>>
>>>
>>> id(lst)
139698366459848
>>> id(res)
139698366152576
>>>
>>>
>>>
>>> res_rev = sorted(lst, reverse=True)
>>>
>>>
>>> res_rev
[5, 4, 3, 2, 1]
>>>
>>>
>>>
>>> res_rev = sorted(lst, reverse=False)
>>>
>>>
>>> res_rev
[1, 2, 3, 4, 5]
>>>
>>>
>>>
>>> lst
[5, 2, 3, 1, 4]
>>>
>>>
>>>
>>> lst.sort()
>>>
>>>
>>> lst
[1, 2, 3, 4, 5]
>>>
>>>
>>> lst = [5,2,3,1,4]
>>>
>>>
>>> lst
[5, 2, 3, 1, 4]
>>>
>>>
>>> lst.sort(reverse=True)
>>>
>>> lst
[5, 4, 3, 2, 1]
>>>
>>> lst = [5,2,3,1,4]
>>>
>>> lst.sort(reverse=False)
>>>
>>>
>>> lst
[1, 2, 3, 4, 5]
>>>
>>>
>>>
>>>
>>>
>>> lst
[1, 2, 3, 4, 5]
>>>
>>>
>>>
>>> lst = [5,2,3,1,4]
>>>
>>>
>>>
>>> lst
[5, 2, 3, 1, 4]
>>>
>>>
>>>
>>>
>>> lst.sort(key=len)
Traceback (most recent call last):
File "", line 1, in
TypeError: object of type 'int' has no len()
>>>
>>>
>>>
>>>
>>>
>>> lst = [ [5], [2,3], [1,4,6] ]
>>>
>>>
>>> lst
[[5], [2, 3], [1, 4, 6]]
>>>
>>>
>>>
>>> lst.sort(key=len)
>>>
>>>
>>> lst
[[5], [2, 3], [1, 4, 6]]
>>>
>>>
>>>
>>> lst.sort(key=len, reverse=True)
>>>
>>>
>>> lst
[[1, 4, 6], [2, 3], [5]]
>>>
>>>
>>> lst.sort(key=len, reverse=False)
>>>
>>>
>>>
>>> lst
[[5], [2, 3], [1, 4, 6]]
>>>
>>>
>>>
>>>
>>>
>>> lst
[[5], [2, 3], [1, 4, 6]]
>>>
>>>
>>>
>>>
>>> sorted(lst)
[[1, 4, 6], [2, 3], [5]]
>>>
>>>
>>>
>>> sorted(lst, reverse=False)
[[1, 4, 6], [2, 3], [5]]
>>>
>>>
>>> sorted(lst, reverse=True)
[[5], [2, 3], [1, 4, 6]]
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> lst = ["fk", "af", "zs"]
>>>
>>>
>>> sorted(lst)
['af', 'fk', 'zs']
>>>
>>>
>>>
>>> sorted(lst, reverse=True)
['zs', 'fk', 'af']
>>>
>>>
>>>
>>> sorted(lst)
['af', 'fk', 'zs']
>>>
>>>
>>>
>>> lst = ["fky", "af", "zsxw"]
>>>
>>>
>>> sorted(lst)
['af', 'fky', 'zsxw']
>>>
>>>
>>>
>>> lst = ["fky", "afxe", "z"]
>>>
>>>
>>>
>>> sorted(lst)
['afxe', 'fky', 'z']
>>>
>>>
>>> sorted(lst, key=len)
['z', 'fky', 'afxe']
>>>
>>>
>>>
>>>
>>> sorted(lst, key=len, reverse=True)
['afxe', 'fky', 'z']
>>>