Find most common element in a 2D list in Python

PythonServer Side ProgrammingProgramming

A 2D list has list as its element. In other words it is a list of lists. In this article we are required to find the element which is most common among all the lists inside a list.

With max and count

We design a follow with a in condition to check for the presence of an element in a given sublist. Then we apply the max function along with the count function to get the the element with maximum frequency.

Example

 Live Demo

def highest_freq(lst):
   SimpleList = [el for sublist in lst for el in sublist]
   return max( SimpleList, key= SimpleList.count)
# Given list
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("Given List:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))

Output

Running the above code gives us the following result −

Given List:
[[45, 20, 11], [20, 17, 45], [20, 13, 9]]
Element with highest frequency:
20

With chain

Here we take a similar approach as the above one. But we use the chain function from the itertools the module.

Example

 Live Demo

from itertools import chain
def highest_freq(lst):
   SimpleList = list(chain.from_iterable(lst))
   return max( SimpleList, key= SimpleList.count)
# Given list
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("Given List:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))

Output

Running the above code gives us the following result −

Given List:
[[45, 20, 11], [20, 17, 45], [20, 13, 9]]
Element with highest frequency:
20

With Counter and chain

In this approach the counter function from collections keeps the count of the element that is retrieved using the chain function from itertools.

Example

 Live Demo

from itertools import chain
from collections import Counter
def highest_freq(lst):
   SimpleList = chain.from_iterable(lst)
   return Counter(SimpleList).most_common(1)[0][0]
# Given list
listA = [[45, 20, 11], [20, 17, 45], [20,13, 9]]
print("Given List:\n",listA)
print("Element with highest frequency:\n",highest_freq(listA))

Output

Running the above code gives us the following result −

Given List:
[[45, 20, 11], [20, 17, 45], [20, 13, 9]]
Element with highest frequency:
20
raja
Published on 04-Jun-2020 11:42:03
Advertisements