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
def mostCommon(lst):
flatList = [el for sublist in lst for el in sublist]
return max (flatList, key = flatList.count)
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
from itertools import chain
def mostCommon(lst):
flatList = list (chain.from_iterable(lst))
return max (flatList, key = flatList.count)
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
from itertools import chain
from collections import Counter
def mostCommon(lst):
flatList = chain.from_iterable(lst)
return Counter(flatList).most_common( 1 )[ 0 ][ 0 ]
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):
count_dict = {}
for row in lst:
for elem in row:
if elem in count_dict:
count_dict[elem] + = 1
else :
count_dict[elem] = 1
return max (count_dict, key = count_dict.get)
lst = [
[ 1 , 2 , 3 ],
[ 2 , 2 , 2 ],
[ 3 , 3 , 1 ]
]
most_common = most_common_element(lst)
print (most_common)
|
# 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]
lst = np.array([[ 10 , 20 , 10 ], [ 30 , 40 , 10 ], [ 50 , 10 , 30 ]])
print (mostCommon(lst))
|
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. Example Make 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
2 min read
Find an Element In a List of Tuples
In Python programming, it is often necessary to locate an element inside a list of tuples. Tuples are arranged collections, and locating a particular piece inside them requires knowledge of a variety of strategies. When data is kept as tuples inside a list, this procedure is essential for data retri
3 min read
Python program to find common elements in three lists using sets
We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}. Using set.intersection()set.intersection() method finds common e
3 min read
Remove common elements from two list in Python
When working with two lists in Python, we may need to remove the common elements between them. A practical example could be clearing out overlapping tasks between two to-do lists. The most efficient way to remove common elements between two lists is by using sets. [GFGTABS] Python a = [1, 2, 3, 4, 5
3 min read
Python - Elements frequency count in multiple lists
Sometimes while working with Python lists we can have a problem in which we need to extract the frequency of elements in list. But this can be added work if we have more than 1 list we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension
6 min read
Python Program to Find Most common elements set
Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements. Examples: Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}Output : {9, 3, 5, 7}Explanation : Resultant
5 min read
Python | Print the common elements in all sublists
Given a list of lists, the task is to find the elements which are common in all sublist. There are various approaches to do this task. Let's discuss the approaches one by one. Method #1: Using set C/C++ Code # Python code to find duplicate element in all # sublist from list of list # List of list in
3 min read
Python - Duplicate Element Indices in List
We are having a list we need to find the duplicate element indices. For example, we are given a list a = [10, 20, 30, 20, 40, 30, 50] we need to find indices of the duplicate items so that output should be {20: [1, 3], 30: [2, 5]}. Using a loop and a dictionaryWe iterate through the list using enume
3 min read