Below is one more solution.
First, a caution is in order. The following two lines are excerpted from PEP 20 - The Zen of Python:
Explicit is better than implicit.
Simple is better than complex.
In that spirit, it is important to write code that is clear to other programmers, whenever that is practical, when that code is aimed at performing real work. However, that does not mean that we cannot write code that performs tricks, as puzzles or for recreational purposes, as we are doing in this thread.
Now with that having been noted, here is a
median function that performs the calculation in one line ...
return sum(sorted(seq)[(len(seq) - 1) // 2: len(seq) // 2 + 1]) / float((len(seq) + 1) % 2 + 1)
The above is rather abstruse, so we must not code like that when we are doing actual work.
EDITED (below) on January 25, 2017 to apply the
float function to the main numerator instead of to the main denominator and to simplify the main denominator ...
return float(sum(sorted(seq)[(len(seq) - 1) // 2: len(seq) // 2 + 1])) / (2 - len(seq) % 2)