sorted() and list.sort() are very useful inbuilt Python functions .
They get even more powerful with the “key” parameter
The key parameter basically allows us to call either another function or some logic, the outcome of which forms the basis of our sorting.
The return value of the key parameter will be used to decide the sort order.
Lets through talk an actual example –
Lets say we are given an input list of names of great personalities from history and we want to sort the names based on the last name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
input_list = [ 'Sachin Tendulkar','Nelson Mandela', 'Mohandas Ghandhi','Napolean Bonaparte'] | |
output_list = ['Napolean Bonaparte','Mohandas Ghandhi','Nelson Mandela', 'Sachin Tendulkar'] |
Step 1:
Write the logic to decide the sort order i.e. sorting based on last name
I wrote a tiny function that will receive a list item and shall return the last name , after splitting the full name string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def last_name(x): | |
return x.split()[1] |
Step 2:
Use the sorting logic as a key parameter in the sorted() function now.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# just call the function's name as the key value ! | |
output_list = sorted(input_list,key= last_name) |
It is as simple as calling the last_name function name as the key and the list will be sorted based on that key’s value.The key’s value acts as a sort of proxy to decide the sorting order .
Bonus learning –
Rather than defining and calling the key logic as a separate function, we can also use Lambda operator to define the key inline.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# use lambda operator to define the key | |
output_list = sorted(output_list,key= lambda x: x.split()[1]) |
Leave a Reply