Change language

# Python | Find the most common item in a 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 the `max()`

Pythonic’s first approach is to use max () Python method. First, we flatten the 2D list and then simply use the max () method to determine the maximum occuring element among all elements.

 ` # Python3 program to find the majority ` ` # common element in 2D list `   ` def ` ` mostCommon (lst): ` ` flatList ` ` = ` ` [el ` ` for ` ` sublist ` ` in ` ` lst ` ` for ` ` el ` ` in ` ` sublist] ` ` retur n ` ` max ` ` (flatList, key ` ` = ` ` flatList.count) `   ` # Driver code ` ` lst ` ` = ` ` [[` ` 10 ` `, ` ` 20 ` `, ` ` 30 ` `], [` ` 20 ` ` , ` ` 50 ` `, ` ` 10 ` `], [` ` 30 ` `, ` ` 50 ` `, ` ` 10 ` `]] ` ` print ` ` (mostCommon (lst)) `

Output :

` 10 `

There is another method to flatten the list like ` chain.from_iterable () ` which gives an alternative approach.

 ` # Python3 program to find the majority ` ` # general item in 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)) `

Output:

` 10 `

Approach # 2 Using ` most_common () ` from Collections

Most_common () is used to create a sequence of n most common input values. So we just flatten the list and find the most common element using the above method.

 ` # Python3 program for finding the majority ` ` # common item in 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)) `

Exit :

` 10 `