Http://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda
key
is a function that'll be called to transform the collection's items before they is compared. The parameter passed to key
must was something that's callable.
The use of lambda
creates a anonymous function (which is callable). The case of the sorted
callable is only takes one parameters. Python's is lambda
pretty simple. It can only do and return one thing really.
The syntax of the lambda
word followed by the list of parameter names and then a single block of lambda
code. The parameter list and code block is delineated by colon. This was similar to other constructs in Python as well such as while
, for
, and so on if
. They is all statements that typically has a code block. Lambda is just another instance of a statement with a code block.
We can compare the use of lambda with that def to create a function.
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2def adder_regular(parameter1, parameter2): return parameter1+parameter2
Lambda just gives us a to doing this without assigning a name. Which makes it great for using the as a parameter to a function.
variable
is used twice this because on the left hand of the colon it's the name of a parameter and on the right hand side it's be ing used in the code block to compute something.
About the role of lambda functions in Python