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>The reason you get the modes twice is that your for-loop loops over every element in the list. Therefore, when it encounters the second instance of a previously seen element, it prints it out again.</p>

<p>In other news, your function will fail for a different reason - try removing the first <code>0</code> and see what happens.</p>

<p>This is how I would fix it:</p>

<pre><code>from collections import Counter

def compute_mode(numbers):
    counts = Counter(numbers)
    maxcount = max(counts.values())
    for num,count in counts:
        if count == maxcount:
            print(num, count)
</code></pre>

<p>If you want to do all the heavy lifting yourself:</p>

<pre><code>def compute_mode(numbers):
    counts = {}
    maxcount = 0
    for number in numbers:
        if number not in counts:
            counts[number] = 0
        counts[number] += 1
        if counts[number] &gt; maxcount:
            maxcount = counts[number]

    for number, count in counts.items():
        if count == maxcount:
            print(number, count)
</code></pre>

python list