There's nothing special about lambda, it's a function that takes one argument, x, and it returns the result of the expression on the right of the colon.
Normally, a function is created with a function statement. Statements have side effects, in the case of a function statement it is that a function gets created and the name you specified will refer to it.
A lambda expression is not a statement, so no side effect, instead the result of the expression is a function.
Likewise, a ternary expression (if-else in an expression) is.. not a statement, it has a result. While an if-statement statement has no result, but a side effect, which is that other statements are executed.
My first piece of code is intentionally a bit difficult to understand, it's just exploiting that the logical operators
orare short-circuited, meaning that if the left hand side (lhs) of the
or-operator is truthy, then that's the result, and the rhs doesn't need to be evaluated at all.
(A value is truthy if converting it to bool evaluates to True)
For example, this will not print anything:
from __future__ import print_function # Make print a function instead of statement
5 or print('this will not print because 5 is truthy')
list.sort always returns
None, which is falsy, so the result of the first
or is that of the rhs which is the rest of the expression. So this remains:
and will not evaluate rhs if lhs is falsy. So if x%2 is 1 (truthy) then
x[y/2] also gets evaluated and its result will probably be truthy, causing that to be the result as the last
or will ignore its rhs.
I say probably, because the result might be 0 which.. means that there's a scenario where my function will calculate an incorrect median!
..Obviously, code should be easy to read, the only useful thing about code like that is understanding how those operators work.
Modules..just google for what you want to do, if the module exists, somebody else will have asked about it as well and it'll turn up as one of the search results.
Regarding time, computing a median requires sorting, and then it's just looking up one or two values which takes a negligible amount of time.
Sorting numbers takes time proportional to k * n where k is the length of the longest number (in number of digits) and n is the length of the list. (radix sort)
But Python's sort takes n * log(n) time because it sorts by comparing values to each other (radix sort can only be used for numbers) So those median functions in numpy and statistics, they just might be using radix sort instead which is a significant improvement for large lists. And that would be more difficult to implement, particularly for floats.