Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Step Frequency of elements in List
Next article icon

Python – Sort by Frequency of second element in Tuple List

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given list of tuples, sort by frequency of second element of tuple.

Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] 
Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] 
Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. 

Input : test_list = [(1, 7), (8, 7), (9, 8), (3, 7)] 
Output : [(1, 7), (8, 7), (3, 7), (9, 8)] 
Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first.

Method #1 : Using sorted() + loop + defaultdict() + lambda

In this, we compute the frequency using defaultdict() and use this result to pass as param to lambda function to perform sorting using sorted() on basis of it.

Python3




# Python3 code to demonstrate working of
# Sort by Frequency of second element in Tuple List
# Using sorted() + loop + defaultdict() + lambda
from collections import defaultdict
 
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# constructing mapping
freq_map = defaultdict(int)
for idx, val in test_list:
    freq_map[val] += 1
 
# performing sort of result
res = sorted(test_list, key = lambda ele: freq_map[ele[1]], reverse = True)
 
# printing results
print("Sorted List of tuples : " + str(res))
 
 
Output
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Sorted List of tuples : [(2, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)]

Time Complexity: O(logn)
Auxiliary Space: O(n)

Method #2 : Using Counter() + lambda + sorted()

In this, the task of frequency computation is done using Counter(), rest all functionality is similar to above method.

Python3




# Python3 code to demonstrate working of
# Sort by Frequency of second element in Tuple List
# Using Counter() + lambda + sorted()
from collections import Counter
 
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# constructing mapping using Counter
freq_map = Counter(val for key, val in test_list)
 
# performing sort of result
res = sorted(test_list, key = lambda ele: freq_map[ele[1]], reverse = True)
 
# printing results
print("Sorted List of tuples : " + str(res))
 
 
Output
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Sorted List of tuples : [(2, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)]

Time complexity: O(n log n), where n is the length of the input list test_list. The sorting operation takes O(n log n) time complexity, and constructing the frequency map using Counter() takes O(n) time complexity. Since O(n log n) is the dominant term.
Auxiliary Space: O(n), where n is the length of the input list test_list. This is because we are using a Counter() to construct a frequency map of the second element of each tuple in the input list, which takes O(n) auxiliary space. Additionally, we are storing the sorted list of tuples in memory, which also takes O(n) auxiliary space. 

Method #3 : Using groupby() + sorted()

In this, the task of frequency computation is done by sorted() and groupby() functions from the itertools module.

Algorithm

Sort the input list of tuples by the second element. Count the frequency of each second element using a dictionary. Sort the input list of tuples by the frequency of the corresponding second element, in reverse order. Return the sorted list.

Python




from itertools import groupby  # import groupby function from itertools module
 
def sort_by_frequency(test_list):  # define function called sort_by_frequency that takes a list called test_list as input
    freq_dict = {val: len(list(group)) for val, group in groupby(sorted(test_list, key=lambda x: x[1]), lambda x: x[1])} 
    # create a dictionary called freq_dict where each key is a unique second element of a tuple in test_list and its value is the number of times that second element appears in test_list
    # we do this by using the groupby function to group the tuples in test_list by their second element, then using len to count the number of tuples in each group
    # we use sorted to sort the list of tuples by their second element before using groupby, and we use a lambda function to specify that we want to group by the second element of each tuple
    # the resulting dictionary has keys that are unique second elements from test_list and values that are the frequency of each second element in test_list
    return sorted(test_list, key=lambda x: freq_dict[x[1]], reverse=True) 
    # sort the original list of tuples (test_list) based on the values in freq_dict
    # we use a lambda function to specify that we want to sort by the value in freq_dict corresponding to the second element of each tuple in test_list
    # we sort the list in reverse order (highest frequency first)
     
test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)]  # define test_list
print("The original list is : " + str(test_list))  # print the original list
print("The sorted list is : " + str(sort_by_frequency(test_list)))  # print the sorted list returned by the sort_by_frequency function
 
 
Output
The original list is : [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] The sorted list is : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)]

Time complexity: O(n log n),where n is the length of test_list
Auxiliary Space: O(n),where n is the length of test_list

Method #4: Using numpy

  • Convert the list of tuples into a numpy array.
  • Use numpy’s argsort function to sort the array based on the frequency of the second element.
  • Use numpy’s take function to get the sorted array based on the argsort indices.
  • Convert the sorted array back to a list of tuples.

Python3




import numpy as np
 
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# convert the list to a numpy array
arr = np.array(test_list)
 
# get the frequency of each second element using numpy's unique function
counts = np.unique(arr[:, 1], return_counts=True)
 
# sort the indices based on the frequency of the second element using numpy's argsort function
sorted_indices = np.argsort(-counts[1])
 
# create an empty array to store the sorted tuples
sorted_arr = np.empty_like(arr)
 
# iterate over the sorted indices and fill in the sorted array
start = 0
for i in sorted_indices:
    freq = counts[1][i]
    indices = np.where(arr[:, 1] == counts[0][i])[0]
    end = start + freq
    sorted_arr[start:end] = arr[indices]
    start = end
 
# convert the sorted array back to a list of tuples
res = [tuple(row) for row in sorted_arr]
 
# printing results
print("Sorted List of tuples : " + str(res))
 
 

Output:

 The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Sorted List of tuples : [(2, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)]

Time complexity: O(n log n) (due to sorting)
Auxiliary space: O(n) (due to creating a numpy array)



Next Article
Python - Step Frequency of elements in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python - Step Frequency of elements in List
    Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
    4 min read
  • Sort List Elements by Frequency - Python
    Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
    3 min read
  • Sort a List of Tuples by Second Item - Python
    The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
    2 min read
  • Python - Elements frequency in Tuple
    Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
    7 min read
  • Python - Elements frequency in Tuple Matrix
    Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
    5 min read
  • Python - Elements Frequency in Mixed Nested Tuple
    Sometimes, while working with Python data, we can have a problem in which we have data in the form of nested and non-nested forms inside a single tuple, and we wish to count the element frequency in them. This kind of problem can come in domains such as web development and Data Science. Let's discus
    8 min read
  • Python - List Frequency of Elements
    We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
    2 min read
  • Python - Sort Tuple List by Nth Element of Tuple
    We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)] Using sorted() with lambdasorted() function wi
    3 min read
  • Python | Finding frequency in list of tuples
    In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let's discuss cert
    6 min read
  • Python - Restrict Tuples by frequency of first element's value
    Given a Tuple list, the task is to write a Python program to restrict the frequency of the 1st element of tuple values to at most K. Examples: Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 2 Output : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4),
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences