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 | Extract unique tuples from list, Order Irrespective
Next article icon

Python – Unique Tuple Frequency (Order Irrespective)

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

Given tuple list, extract the frequency of unique tuples in list order irrespective.

Input : test_list = [(3, 4), (1, 2), (4, 3), (3, 4)]  Output : 2  Explanation : (3, 4), (4, 3), (3, 4) makes 1 and (1, 2) is 2nd unique element. 
Input : test_list = [(3, 7), (1, 2), (4, 3), (5, 6)]  Output : 4  Explanation : All are different in any order.

Method #1 : Using tuple() + generator expression + sorted() + len() 

The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(), to remove order constraints. The len() is used to compute size. 

Python3




# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using tuple() + list comprehension + sorted() + len()
 
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using tuple() + list comprehension + sorted() + len()
# Size computed after conversion to set
res = len(list(set(tuple(sorted(sub)) for sub in test_list)))
 
# printing result
print("Unique tuples Frequency : " + str(res))
 
 
Output : 
The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)] Unique tuples Frequency : 3

Time Complexity: O(nlogn) where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list 

Method #2: Using map() + sorted() + tuple() + set() + len() 

The combination of the above functions can be used to solve this problem. In this, we perform the task of extending sorting logic and tuple conversion using map(), set() is used to eliminate duplicates and len() is used to find the length of the container. 

Python3




# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using map() + sorted() + tuple() + set() + len()
 
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using map() + sorted() + tuple() + set() + len()
# inner map used to perform sort and outer sort to
# convert again in tuple format
res = len(list(set(map(tuple, map(sorted, test_list)))))
 
# printing result
print("Unique tuples Frequency : " + str(res))
 
 
Output : 
The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)] Unique tuples Frequency : 3

Method#3: Using Recursive method.

This method works by recursively calling itself with the remaining elements of the input list after the first element is removed. It then checks if the first element is unique by comparing it to the sorted version of each of the remaining elements. If the first element is unique, it adds 1 to the frequency returned by the recursive call. If it is not unique, it simply returns the frequency returned by the recursive call. The base case is when the input list is empty, in which case the frequency is 0.

Python3




def unique_tuple_frequency(test_list):
   
    # base case
    if len(test_list) == 0:
        return 0
 
    # recursive call
    rest_freq = unique_tuple_frequency(test_list[1:])
 
    # check if the first element is unique
    for t in test_list[1:]:
        if sorted(test_list[0]) == sorted(t):
            return rest_freq
 
    # if the first element is unique, add 1 to the frequency
    return rest_freq + 1
 
 
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# printing original list
print("The original list is :" + str(test_list))
 
# Using map() + sorted() + tuple() + set() + len()
# inner map used to perform sort and outer sort to
# convert again in tuple format
res = unique_tuple_frequency(test_list)
 
# printing result
print("Unique tuples Frequency : " + str(res))
 
 
Output
The original list is :[(3, 4), (1, 2), (4, 3), (5, 6)] Unique tuples Frequency : 3

Time Complexity: O(N * MlogM)

Sorting each tuple: O(MlogM) where M is the size of the tuple.
Comparing each tuple to the first tuple: O(N * M) where N is the length of the input list and M is the size of the tuple.
Overall time complexity: O(N * MlogM)

Auxiliary Space: O(N * M)

Recursive call stack: O(N)
Creating a new list of remaining elements for each recursive call: O(N * M)

Method #4: Using dictionary and loop

Steps:

  1. Initialize an empty dictionary “freq_dict” to store the frequency of each unique tuple.
  2. Loop through each tuple in the input list “test_list”.
  3. Sort the tuple using sorted() and convert it to a tuple again using tuple(). This will give us a sorted version of the tuple, which we can use to check if it is unique.
  4. Check if the sorted tuple exists as a key in the “freq_dict”.
  5. If it does, increment the value of the corresponding key in “freq_dict”.
  6. If it does not, add the sorted tuple as a key to “freq_dict” with a value of 1.
  7. Finally, return the length of “freq_dict”, which will give us the number of unique tuples in “test_list”.

Python3




def unique_tuple_frequency(test_list):
   
    freq_dict = {}
    for tup in test_list:
        sorted_tup = tuple(sorted(tup))
        if sorted_tup in freq_dict:
            freq_dict[sorted_tup] += 1
        else:
            freq_dict[sorted_tup] = 1
    return len(freq_dict)
 
# Initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
 
# Printing original list
print("The original list is :" + str(test_list))
 
# Using dictionary and loop
res = unique_tuple_frequency(test_list)
 
# Printing result
print("Unique tuples Frequency : " + str(res))
 
 
Output
The original list is :[(3, 4), (1, 2), (4, 3), (5, 6)] Unique tuples Frequency : 3

Time complexity: O(nlogn), where n is the length of the input list “test_list”.
Auxiliary space: O(n), where n is the length of the input list “test_list”. 



Next Article
Python | Extract unique tuples from list, Order Irrespective
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python | Extract unique tuples from list, Order Irrespective
    Sometimes, while working with data, we can have a problem in which we need to check for similar records and eradicate them. When elements are ordered, this case has been discussed before. But sometimes, we might have to ignore the order and has to be removed in case similar elements occur. Let's dis
    5 min read
  • Python - Tuple List intersection (Order irrespective)
    Given list of tuples, perform tuple intersection of elements irrespective of their order. Input : test_list1 = [(3, 4), (5, 6)], test_list2 = [(5, 4), (4, 3)] Output : {(3, 4)} Explanation : (3, 4) and (4, 3) are common, hence intersection ( order irrespective). Input : test_list1 = [(3, 4), (5, 6)]
    6 min read
  • Python - Test for Unique Frequencies
    Given a list, find if frequencies of each element of values are in itself unique values. Input : test_list = [4, 3, 2] Output : False Explanation : All have 1 as frequency, hence duplicacy, hence False Input : test_list = [4, 3, 3, 2, 2, 2] Output : True Explanation : 1, 2, 3 are frequencies of 4, 3
    7 min read
  • Python | Get unique tuples from list
    Sometimes, while working with Python list, we can come across a problem in which we require to find the unique occurrences of list. Having elementary data types is easy to handle, but sometime, we might have complex data types and the problem becomes new in that cases. Let's discuss certain ways in
    3 min read
  • Python - Order Tuples by List
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform ordering of all the tuples keys using external list. This problem can have application in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Input : test_lis
    7 min read
  • Python - Unique Kth positioned tuples
    Sometimes, while working with Python records, we can have a problem in which we need to extract only the unique tuples, based on some particular index of tuples. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this task can be perfor
    8 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 - Maximum frequency in Tuple
    Sometimes, while working with Python tuples, we can have a problem in which we need to find the maximum frequency element in the tuple. Tuple, being quite a popular container, this type of problem is common across the web development domain. Let's discuss certain ways in which this task can be perfo
    5 min read
  • Python | How to get unique elements in nested tuple
    Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let's discuss certain ways in which this problem can be solved. Method #1: Usi
    7 min read
  • Python - Values frequencies of key
    Sometimes, while working with Python dictionary lists, one can have a problem in which we require to find the frequency of all the values occurring in a specific key in dictionary list. This can have application across many domains including web development. Let's discuss certain ways in which this
    7 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