In this article we will discuss how to sort a list of tuple using 2nd or i th item of tuple.

Suppose we have a list of tuple i.e. words and thier frequency count,

Now if we directly call the sort() method on this list i.e.

Then it will sort it using first item of tuple i.e.

But if we want to sort it using 2nd item of tuple i.e. Frequency count i.e.

Let’s see how to do that,

Sort a List of Tuple by 2nd Item of tuple using Lambda function

For sorting a list of tuples by 2nd item or ith item, we need to pass our custom comparator i.e. key function in the sort(),

What is a Key Function ?

While sorting a list, all the elements of list will be compared with each other. But before comparison it will call the key function on each entry, to determine what portion of the object will compared.

In other words, on passing element to key function, it will return the element that should be used for comparing the elements in list while sorting.

Now let’s see how to sort List of tuple by 2nd Item using Lambda Function as Key Function i.e.

Now, lists content will be,

Sort a List of Tuple by 2nd Item of tuple using Custom Function as Comparator

First define a function that accepts a tuple and returns second element from it i.e.

Now use this function as key function in sorting the list of tuples i.e.

It will sort the list by 2nd item of tuple i.e.

Complete example is as follows,



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.