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 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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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]))

chevron_right


Output :

The original tuple : (6, 7, 8, 6, 7, 10)
Maximum element frequency tuple : 6



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.