Mean, median, and mode

Paul McGuire ptmcg at
Mon Dec 6 20:34:06 CET 2004

"Paul McGuire" <ptmcg at> wrote in message
news:E01td.116586$jq5.8973 at
> This median expression is incorrect.  median is *not* the midpoint between
> max and min values.  It is the middle value when all values are sorted
> an odd number of values), or the average of the two middle values when all
> values are sorted (for an even number of values).
> In Python 2.4 (needed to use sorted() built-in), this can be one-lined as:
> median = lambda x: ((x % 2) and (sorted(x)[len(x)>>1]) or
> (sum(sorted(x)[(len(x)>>1):(len(x)>>1)+1])/2))
> (not yet tested, as I've not installed v2.4 yet)
> With boolean short-circuiting, this should only sort the list once.
> -- Paul
Damned off-by-one errors!

Try this instead:

median = lambda x: ((len(x) % 2) and (sorted(x)[(len(x)>>1)-1]) or

Or using the sneaky None returned by sort(), for pre-2.4 utility:

median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)-1]) or

-- Paul

More information about the Python-list mailing list