Syntax: sorted (repeatable, key, reverse)
Parameters: sort takes three parameters, of which two are optional. p >
Output: Sorted List returned: [1, 2, 3, 4, 6 , 7, 8] Reverse sort: [8, 7, 6, 4, 3, 2, 1] Original list not modified: [2, 8, 1, 4, 6, 3, 7]
Example 2: sorting different data types
Output : ['e',' q', 'r',' t', 'w',' y'] ['e',' q', 'r',' t', 'w' , 'y'] [' h', 'n',' o', 'p',' t', 'y'] [' e', 'q',' r', 't',' w' , 'y'] [' e', 'q',' r', 't',' w', 'y'] [' e', 'q',' r', 't',' w' , 'y']
Selective sorting by key parameter
The sorted () function has an optional key parameter that accepts a function as a value. This key function converts each element before sorting, it takes a value and returns 1 value, which is then used in the sort instead of the original value.
For example, if we pass a list of strings to sorted (), it is sorted alphabetically. But if we specify key = len, i.e. we give len as a key, the strings will be passed to len, and the value it returns, i.e. the length of the lines will be sorted. This means the lines will be sorted by length instead of
Output: Normal sort: ['aaa',' b', 'cccc',' dd'] Sort with len: ['b',' dd', 'aaa',' cccc']
The key also accepts custom functions as the value to sort.
Output: Normal sort: [3, 7, 11, 15] Sorted with key: [7, 15, 3, 11]
This article is provided by Harshit Agrawal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.