find the mode of all elements in an array in python

To find the mode of all elements in an array in Python, there are two ways to do it. The easiest way is to use the mode() function from the statistics module. Alternatively, we can use the Counter object from the collections module to count the frequency of each element in the array, and then find the most common element.

Using the statistics module:

main.py
import statistics

arr = [1, 2, 3, 4, 4, 5, 5, 5, 5]

mode = statistics.mode(arr)

print("Mode of the array is:", mode)
120 chars
8 lines

Output:

main.py
Mode of the array is: 5
24 chars
2 lines

Using Counter object:

main.py
from collections import Counter

arr = [1, 2, 3, 4, 4, 5, 5, 5, 5]

counter = Counter(arr)

mode = counter.most_common()[0][0]

print("Mode of the array is:", mode)
165 chars
10 lines

Output:

main.py
Mode of the array is: 5
24 chars
2 lines

Both of these methods return the mode of the array, which is the most common element in the array. If there are multiple elements with the same frequency, both methods will return the first element encountered with that frequency.

gistlibby LogSnag