1

I'm trying to find the most occurring number in a tuple and assign that value to a variable. I tried the following code, but it gives me the frequency and the mode, when I only need the mode.

from collections import Counter
self.mode_counter = Counter(self.numbers)
self.mode = self.mode_counter.most_common(1)

print self.mode

Is there a way to just assign the mode to self.mode using Counter?

JeremyM
  • 35
  • 1
  • 6
  • Here's an answer for a similar question with interesting soluitions: [link](http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list) – Maciek Jan 10 '14 at 15:16

2 Answers2

4

Just unpack the return value of most_common.

[(mode, _)] = mode_counter.most_common(1)
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

most_common(1) returns a list of 1 tuple.

You have two possibilities:

Use self.mode, _ = self.mode_counter.most_common(1)[0] to discard the second value

Use self.mode = self.mode_counter.most_common(1)[0][0] to only get the first value

sphere
  • 1,330
  • 13
  • 24