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

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 tupletest_tuple = (6, 7, 8, 6, 7, 10)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Maximum frequency in Tuple# Using loop + count()cnt = 0res = test_tuple 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() + lambdafrom collections import Counter  # initializing tupletest_tuple = (6, 7, 8, 6, 7, 10)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Maximum frequency in Tuple# Using max() + Counter() + lambdares = max(Counter(test_tuple).items(), key = lambda ele : 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

My Personal Notes arrow_drop_up