Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean: key=lambda x: x[1] ?

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]) 
like image 668
Nyxynyx Avatar asked Apr 30 '13 22:04

Nyxynyx


People also ask

What does Key lambda mean?

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).

What does lambda X X do?

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.

What is lambda function in Python?

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.


1 Answers

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.

like image 149
cdhowie Avatar answered Sep 28 '22 02:09

cdhowie