
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Most Common Element in a 2D List in Python
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
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
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
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