Skip to content
Related Articles

Related Articles

Improve Article
Python | Find most common element in a 2D list
  • Last Updated : 29 Apr, 2019

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.

Examples:

Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
Output : 10

Input : [['geeks', 'wins'], ['techie', 'wins']]
Output : wins

Approach #1 : Using max() function

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.




# Python3 program to find most 
# common element in a 2D list
  
def mostCommon(lst):
    flatList = [el for sublist in lst for el in sublist]
    return max(flatList, key = flatList.count)
              
# Driver code
lst = [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
print(mostCommon(lst))
Output:



10

There is another method to flatten the list i.e chain.from_iterable() which gives rise to an alternative approach.




# Python3 program to find most 
# common element in a 2D list
from itertools import chain
  
def mostCommon(lst):
    flatList = list(chain.from_iterable(lst))
    return max(flatList, key=flatList.count)
  
# Driver code
lst = [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
print(mostCommon(lst))
Output:
10

 
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.




# Python3 program to find most 
# common element in a 2D list
from itertools import chain
from collections import Counter
  
def mostCommon(lst):
    flatList = chain.from_iterable(lst)
    return Counter(flatList).most_common(1)[0][0]
              
# Driver code
lst = [[10, 20, 30], [20, 50, 10], [30, 50, 10]]
print(mostCommon(lst))
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




My Personal Notes arrow_drop_up
Recommended Articles
Page :