mode function in python

Oddly, there seems to be no mode function in the python standard library. It feels like something that should have an optimized C version squirreled away somewhere. ‘Mode’ is too ambiguous to be easily searchable, alas. Anyway, here’s a version that should be reasonably fast

from collections import defaultdict
def mode(iterable):
    counts = defaultdict(int)
    for item in iterable:
        counts[item] += 1
    return max(counts, key = counts.get)

Should be reasonably fast (for pure-python), though could eat up a lot of memory on an iterable contaning large items.

Leave a comment

Your email address will not be published. Required fields are marked *