Actual parameters in Python lambda expressions -
i having difficulties understanding concept in python, particularly related use of lambda functions. refer example used in official python documentation.
here example: (found here)
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key=lambda pair: pair[1]) >>> pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
i understand functionality of lambda itself, being anonymous function. don't understand how accepts arguments opposed normal callable function: add(x,y)
, x
, y
here actual parameters sent input add()
function, while formal parameters seen in function definition can like:
def add(val1, val2): return val1 + val2
but in first example above, actual parameter sent lambda? when pair
formal parameter (which can take name of course.)
lambda pair: pair[1]
equivalent function definition following:
def lambda_equivalent (pair): return pair[1]
so pair
parameter anonymous lambda function accepts. has 1 parameter.
the function passed argument key
parameter of list.sort
function. again equivalent following:
pairs.sort(key=lambda_equivalent)
what list.sort
call key
function every item determine actual value list items should sorted by. list.sort
call key((1, 'one'))
, key((2, 'two'))
, etc., list item—the tuple—is parameter passed key function. in case of lambda, pair
.
Comments
Post a Comment