Python counting multiple modes in a list
<p>This is a simple function but it is giving me a hard time. I'm trying to calculate the mode in a list, and if there are > 1 modes (with the same frequency), then they need to be displayed. </p>

<pre><code>def compute_mode(numbers):
mode = 0
count = 0
maxcount = 0
for number in numbers:
    count = numbers.count(number)
    if count &gt;= maxcount:
        maxcount = count
        mode = number
        print("Mode: ", mode, "Count: ", maxcount)
</code></pre>

<p>Function call:</p>

<pre><code>print(compute_mode([0,1,3,5,7,3,0]))
</code></pre>

<p>Output:</p>

<pre><code>Mode:  0 Count:  2
Mode:  3 Count:  2
Mode:  3 Count:  2
Mode:  0 Count:  2
</code></pre>

<p>I can't seem to make the function not repeat the last two lines. I'm not sure why it is repeating again for 0 and 3.</p>

<p>Any ideas?</p>

<p>Its repeating those lines, simply because you have 2 of those numbers in your list.</p>

<p>Your function doesn't track if its already seen a number, in order to update a counter for it.</p>

<p>To count things, use the appropriately named <code>Counter</code> from the <code>collections</code> module:</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt;&gt; Counter([0,1,3,5,7,3,0]).most_common()
[(0, 2), (3, 2), (1, 1), (5, 1), (7, 1)]
</code></pre>

<p>Or, the other way to do this is to keep track of a number you have already seen, and just update its counter in a dictionary (which is similar to how <code>Counter</code> works), using a <code>defaultdict</code>:</p>

<pre><code>&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt; d = defaultdict(int)
&gt;&gt;&gt; for i in [0,1,3,5,7,3,0]:
...   d[i] += 1
...
&gt;&gt;&gt; d
defaultdict(&lt;class 'int'&gt;, {0: 2, 1: 1, 3: 2, 5: 1, 7: 1})
&gt;&gt;&gt; for item, count in d.items():
...    print('Mode: {} Count: {}'.format(item, count))
...
Mode: 0 Count: 2
Mode: 1 Count: 1
Mode: 3 Count: 2
Mode: 5 Count: 1
Mode: 7 Count: 1
</code></pre>

python list