Search code examples
pythoncollectionscountermode

How do I find the mode of a list or tuple without the frequency?


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?


Solution

  • 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