Write a Python program to Sort by Frequency of second element in Tuple List


This program sorts a list of tuples based on the frequency of occurrence of the second element in each tuple. Here's what happens step-by-step:

  • The val list is defined and initialized with 6 tuples, each containing two values.
  • The original val list is printed using the following line:
    • print("Original List : " , val)
  • The Counter function from the collections module is used to count the frequency of occurrence of each tuple in the val list. The val list is passed to Counter as an argument in a generator expression:
    • freq = Counter(val for key, val in val)
  • The sorted list of tuples, res, is created by using the sorted function with a key argument that specifies the frequency of occurrence of the second element in each tuple. The lambda function lambda e: freq[e[1]] is used as the key, where e is a tuple in the val list and e[1] is the second element of the tuple. The reverse argument is set to True, so the tuples are sorted in descending order based on their frequency:
    • res = sorted(val, key = lambda e: freq[e[1]], reverse = True)
  • The sorted list of tuples, res, is printed using the following line:
    • print("Sorted List of tuples : " , res)

So the program takes a list of tuples, counts the frequency of occurrence of each tuple, and then sorts the list based on the frequency of the second element in each tuple.

Source Code

from collections import Counter
val = [ (2, 7), (3, 7), (2, 5), (8, 7), (6, 5), (9, 8)]
print("Original List : " , val)
freq = Counter(val for key, val in val)
res = sorted(val, key = lambda e: freq[e[1]], reverse = True)
print("Sorted List of tuples : " , res)

Output

Original List :  [(2, 7), (3, 7), (2, 5), (8, 7), (6, 5), (9, 8)]
Sorted List of tuples :  [(2, 7), (3, 7), (8, 7), (2, 5), (6, 5), (9, 8)]


Example Programs