I see it used in sorting, but what do the individual components of this line of code actually mean?
key=lambda x: x[1]
What's lambda
, what is x:
, why [1]
in x[1]
etc...
Examples
max(gs_clf.grid_scores_, key=lambda x: x[1]) sort(mylist, key=lambda x: x[1])
In Python, lambda is a keyword used to define anonymous functions(i.e., functions that don't have a name), sometimes called lambda functions (after the keyword, which in turn comes from theory).
The whole lambda function lambda x : x * x is assigned to a variable square in order to call it like a named function. The variable name becomes the function name so that We can call it as a regular function, as shown below. The expression does not need to always return a value.
Python Lambda Functions are anonymous function means that the function is without a name. As we already know that the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
lambda
effectively creates an inline function. For example, you can rewrite this example:
max(gs_clf.grid_scores_, key=lambda x: x[1])
Using a named function:
def element_1(x): return x[1] max(gs_clf.grid_scores_, key=element_1)
In this case, max()
will return the element in that array whose second element (x[1]
) is larger than all of the other elements' second elements. Another way of phrasing it is as the function call implies: return the max element, using x[1]
as the key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With