Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Python – Maximum frequency in Tuple

  • Last Updated : 22 Jun, 2020

Sometimes, while working with Python tuples, we can have a problem in which we need to find the maximum frequency element in tuple. Tuple, being quite popular container, this type of problems are common across web development domain. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (6, 7, 10, 11, 10)
Output : 10

 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

Input : test_tuple = (5, 5, 5)
Output : 5



Method #1 : Using count() + loop
The combination of above functions can be used to solve this problem. This is brute force approach to solve this problem. In this, we use count() to perform counting of elements.




# Python3 code to demonstrate working of 
# Maximum frequency in Tuple
# Using loop + count()
  
# initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Maximum frequency in Tuple
# Using loop + count()
cnt = 0
res = test_tuple[0
for ele in test_tuple: 
    curr_freq = test_tuple.count(ele) 
    if(curr_freq> cnt): 
        cnt = curr_freq 
        res = ele 
          
# printing result 
print("Maximum element frequency tuple : " + str(res))
Output :
The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6

 

Method #2 : Using max() + Counter() + lambda
The combination of above functions can be used to solve this problem. In this, we use Counter() to find the frequency of all elements and max() is used to find maximum of it.




# Python3 code to demonstrate working of 
# Maximum frequency in Tuple
# Using max() + Counter() + lambda
from collections import Counter
  
# initializing tuple
test_tuple = (6, 7, 8, 6, 7, 10)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Maximum frequency in Tuple
# Using max() + Counter() + lambda
res = max(Counter(test_tuple).items(), key = lambda ele : ele[1])
          
# printing result 
print("Maximum element frequency tuple : " + str(res[0]))
Output :
The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6



My Personal Notes arrow_drop_up
Recommended Articles
Page :