Performing sorting on sub strings in Python 3.x using “key” parameter

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.

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

Step 2:

Use the sorting logic as a key parameter in the sorted() function now.

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.

Leave a Reply