Highlights

Subscribe

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 4.25

« Still putting out | Main | How do you describe a face? »

python mode function

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 will-have-to-do-for-now version:

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.