1

Suppose I have an array

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

What would be the most efficient and "pythonic" way to find the item with the most occurrences and how many times it occurs in the list?

aayush
  • 157
  • 7

1 Answers1

2

What would be the most efficient and "pythonic" way to find the item with the most occurrences and how many times it occurs in the list?

Use Collections.Counter to get a dict of each element with value as their occurrence and use most_common for finding the element having highest occurence. Try this:

import collections

arr = [1,2,3,4,5,3]
counts = collections.Counter(arr)

print("Counter:", counts)
# counts.most_common()   # Returns all unique items and their counts
print("Most Occurred:", counts.most_common(1)[0][0])  # Returns the highest occurring item

Outpus:

Counter: Counter({3: 2, 1: 1, 2: 1, 4: 1, 5: 1})
Most Occurred: 3
abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • Hi, thanks for the answer. When I run this, I get: `Counter({2: 2, 1: 1, 3: 1})`. How would I proceed with storing the number of occurrences of the mode, which is 2, in a variable. – aayush Jul 21 '20 at 05:35
  • I have updated as well. – abhiarora Jul 21 '20 at 05:36