the reluctant tester

Perpetual learner of the craft of Software Testing,Servant Leadership and creating better Teams


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.


input_list = [ 'Sachin Tendulkar','Nelson Mandela', 'Mohandas Ghandhi','Napolean Bonaparte']
output_list = ['Napolean Bonaparte','Mohandas Ghandhi','Nelson Mandela', 'Sachin Tendulkar']

view raw

key.py

hosted with ❤ by GitHub

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


def last_name(x):
return x.split()[1]

view raw

split.py

hosted with ❤ by GitHub

Step 2:

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


# just call the function's name as the key value !
output_list = sorted(input_list,key= last_name)

view raw

sorted.py

hosted with ❤ by GitHub

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.


# use lambda operator to define the key
output_list = sorted(output_list,key= lambda x: x.split()[1])

view raw

lambda.py

hosted with ❤ by GitHub



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

About Me

I’m Sunjeet Khokhar

An experienced People Leader,Practice Lead  and Test Manager .

I am driven by the success of people around me, am a keen student of organisational behaviour and firmly believe that we can be better craftspeople by being better humans first.

CoNNECT with Me

%d bloggers like this: