Skip to content
Related Articles

Related Articles

Improve Article

Python – Unique Tuple Frequency (Order Irrespective)

  • Last Updated : 30 Aug, 2020
Geek Week

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 constraint. The len() is used to compute size.




# 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

 

Method #2 : Using map() + sorted() + tuple() + set() + len()
The combination of 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 container.




# 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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :