Python: How to sort a list of tuples by 2nd Item using Lambda Function or Comparator

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,

# List of tuples i.e. word and its frequency count    
wordFreq = [ ('the' , 34) , ('at' , 23), ('should' , 1) , ('from' , 3) ]

Now if we directly call the sort() method on this list i.e.
'''
By default sort() function will sort the list of tuple by first item in tuple
'''    
wordFreq.sort()

Then it will sort it using first item of tuple i.e.
[('at', 23), ('from', 3), ('should', 1), ('the', 34)]

But if we want to sort it using 2nd item of tuple i.e. Frequency count i.e.
('should', 1)
('from', 3)
('at', 23)
('the', 34)

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(),

wordFreq.sort(key=KeyFunction())

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.

Advertisements

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.

'''
Sort List of tuple by 2nd Item of tuple, using Lambda Function as key function
'''
wordFreq.sort(key=lambda elem: elem[1])

Now, lists content will be,
[('should', 1), ('from', 3), ('at', 23), ('the', 34)]

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.

def comparator( tupleElem ) :
    return tupleElem[1]

Now use this function as key function in sorting the list of tuples i.e.
'''
Sort List of tuple by 2nd Item of tuple, using custom function or Comparator
'''
wordFreq.sort(key=comparator)

It will sort the list by 2nd item of tuple i.e.
[('should', 1), ('from', 3), ('at', 23), ('the', 34)]

Complete example is as follows,
def comparator( tupleElem ) :
    return tupleElem[1]

def main():

    # List of tuples i.e. word and its frequency count    
    wordFreq = [ ('the' , 34) , ('at' , 23), ('should' , 1) , ('from' , 3) ]

    # Print list of tuples    
    print(wordFreq)

    print("Sorting List of tuple by first item of tuple")
    
    '''
    By default sort() function will sort the list of tuple by first item in tuple
    '''    
    wordFreq.sort()    
    
    print(wordFreq)
    
    print("Sorting List of tuple by 2nd item of tuple")
        
    '''
    Sort List of tuple by 2nd Item of tuple, using Lambda Function as key function
    '''
    wordFreq.sort(key=lambda elem: elem[1])
    
    print(wordFreq)
    
    '''
    Sort List of tuple by 2nd Item of tuple, using custom function or Comparator
    '''
    wordFreq.sort(key=comparator)
    
    # Print list of tuples
    print(wordFreq)
    
    
if __name__ == '__main__':
    main()


Output:
[('the', 34), ('at', 23), ('should', 1), ('from', 3)]
Sorting List of tuple by first item of tuple
[('at', 23), ('from', 3), ('should', 1), ('the', 34)]
Sorting List of tuple by 2nd item of tuple
[('should', 1), ('from', 3), ('at', 23), ('the', 34)]
[('should', 1), ('from', 3), ('at', 23), ('the', 34)]

 

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top