Python | Find most common element in a 2D list

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

10

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

10


My Personal Notes arrow_drop_up


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.