Python | Find most common element in a 2D list
Last Updated :
09 May, 2023
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
# 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))
There is another method to flatten the list i.e chain.from_iterable() which gives rise to an alternative approach.
Python3
# 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))
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
# 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))
#Approach 3:
The most_common_element() function takes a 2D list as input and returns the most common element in the list.
In this example, we define a 2D list lst and pass it to the most_common_element() function. The function counts the occurrences of each element in the list and returns the most common element, which is 2 in this case. Finally, we print the most common element to the console.
Note that if there are multiple elements with the same maximum count, the max() function will return one of them arbitrarily. If you need to find all the most common elements, you can iterate over the dictionary and check which keys have the maximum value.
Approach:
1.Create an empty dictionary count_dict to keep track of the count of each element.
2.Traverse through each element in the 2D list using two nested loops.
3.For each element, check if it is already present in the count_dict dictionary.
4.If the element is present, increment its count by 1.
5.If the element is not present, add it to the dictionary with a count of 1.
6.After all elements have been counted, find the key with the highest count in the dictionary using the max() function and the key argument set to count_dict.get.
7.Return the key with the highest count.
Python3
def most_common_element(lst):
"""
Returns the most common element in a 2D list.
"""
count_dict = {}
# Traverse through each element in the list and keep track of the count of each element
for row in lst:
for elem in row:
if elem in count_dict:
count_dict[elem] += 1
else:
count_dict[elem] = 1
# Find the key with the highest count in the dictionary and return it
return max(count_dict, key=count_dict.get)
# Example usage
lst = [
[1, 2, 3],
[2, 2, 2],
[3, 3, 1]
]
most_common = most_common_element(lst)
print(most_common) # Output: 2
# Time complexity: O(M*N), where M is the number of rows and N is the number of columns in the list.
# The function traverses through each element in the list once.
# For each element, the function performs a constant amount of work, which takes O(1) time.
# Therefore, the total time complexity of the function is O(M*N).
# Auxiliary Space: O(K), where K is the number of unique elements in the list.
# The function uses a dictionary to store the count of each element, which takes O(K) space.
# The function also uses a constant amount of space for variables and function calls, which takes O(1) space.
# Therefore, the total space complexity of the function is O(K).
Approach #4: Using numpy module
Algorithm:
Create two arrays, "values" and "counts", using the np.unique() function on the input array "arr". The "values" array contains the unique values in "arr" and the "counts" array contains the frequency of each unique value in "arr".
Find the index of the maximum value in the "counts" array using the np.argmax() function.
Return the value at the index found in step 2 in the "values" array.
Python
import numpy as np
def mostCommon(arr):
values, counts = np.unique(arr, return_counts=True)
index = np.argmax(counts)
return values[index]
#DRIVER CODE
lst = np.array([[10, 20, 10], [30, 40, 10], [50, 10, 30]])
print(mostCommon(lst)) # Output: 10
Time complexity:
The time complexity of the np.unique() function is O(nlogn), where n is the size of the input array. The time complexity of the np.argmax() function is O(n), where n is the size of the input array. Therefore, the overall time complexity of the algorithm is O(nlogn + n), which simplifies to O(nlogn).
Auxiliary Space:
The space complexity of the algorithm is O(n), where n is the size of the input array. This is because the np.unique() function creates two arrays of size n, "values" and "counts", to store the unique values and their frequency. The np.argmax() function uses constant space. Therefore, the overall space complexity of the algorithm is O(n).
Similar Reads
Find Most Common Element in Each Column in a 2D List - Python We are given a matrix named m= m = [[1, 2, 3], [4, 2, 3],[1, 5, 3],[4, 2, 6]] we need to count the most common element in each column in the matrix we so that the output in this case will be [1,2,3]. We can do this by using multiple function like Counter from colleciton library and defaultdict. Usin
3 min read
Python | Find common elements in list of lists The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
6 min read
Python | Find most frequent element in a list Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python.ExampleMake a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we f
2 min read
Python | Check if two lists have any element in common Checking if two lists share any common elements is a frequent requirement in Python. It can be efficiently handled using different methods depending on the use case. In this article, we explore some simple and effective ways to perform this check.Using set IntersectionSet intersection uses Python's
3 min read
Python - Print all common elements of two lists Finding common elements between two lists is a common operation in Python, especially in data comparison tasks. Python provides multiple ways to achieve this, from basic loops to set operations. Let's see how we can print all the common elements of two listsUsing Set Intersection (Most Efficient)The
3 min read