The lambda function in your example determines which item comes first.
In a "classical"-situation it would simply calculate x-y: if the result is negative it means that x is smaller then y and therefore comes before y.
Additionally you may pass a reverse-parameter to the sort-method, which would reverse=True the order.
Your "sort"-function is in this case the cmp-function in the "lambda-wrapper". Therein you swap the order of x with y and use the 3rd argument, which means it sorts in a reversed order(x/y-swap) and does it by comparing all the 3rd arguments(x[2]).
Regarding your 2nd bullet:
... could anybody explain what the lambda function does"
If your asking what a lambda-function is: It's an anonymous light-weight inline function. Anonymous means it doesn't have an identifier. (But you could assign one. e.g.: sqr = lambda x : x**2 which you could use now like any other function: y = sqr(2))
Normal function: def name(arg): vs lambda-function: lambda arg: ret_value
^ ^ ^ ^ ^ ^ ^
a) b) c) a) b) c) d)
- a) keyword marking the following as a normal/lambda-function
- b) function-name in case of the lambda functio "missing" therefore
anonymous
- c) function arguments: normal function ->brackets, lambda-function -> without
- d) return value - in case of the normal function omitted, because
must be explicitly returned with return. (without explicit return it
delivers None) The lambda implicitly returns the result of the
evaluation on the right side of the colon.
Your example of the sort-function use is a typical use-case for lambda-functions. They are used as "throw-away" functions, which you may inline without to create a own normal function.
A more "pythonic" variation would be something like:
from operator import itemgetter
keyfunc = itemgetter(2) # takes the 3rd argument from an itterable
sorted_list = sorted(lol, key=keyfunc, reverse=True)
cmpparameter is only supported for backward compatibility. It's been removed from Python3. Always usekey=instead. If you have a tricky case where a key function won't work usefunctools.cmp_to_keyhelper