Given a 2D list (may or may not be of same length), write a Python program to find the most common element in the given 2D list.
Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]] Output : 10 Input : [['geeks', 'wins'], ['techie', 'wins']] Output : wins
Approach #1 : Using
First Pythonic approach is to use max() method of Python. We first flatten the 2D list and then simply apply max() method to find out the maximum occurring element among all the elements.
There is another method to flatten the list i.e
chain.from_iterable() which gives rise to an alternative approach.
Approach #2 : Using
most_common() from collections module
most_common() is used to produce a sequence of the n most frequently encountered input values. Therefore, we simply flatten the list and find the most common element using above mentioned method.
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