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 : 10Attention 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 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[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)) |
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[1]) # printing result print("Maximum element frequency tuple : " + str(res[0])) |
The original tuple : (6, 7, 8, 6, 7, 10) Maximum element frequency tuple : 6

