Possible Duplicate:
What is a lambda and what is an example implementation?
Here is the code for a lambda (from Byte of Python):
def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print twice('word')
print twice(5)
The output is this:
wordword
10
Can someone please explain how the lambda works in longform? how are word and 5 passed to s in the lambda function?
thanks.
As Jake described already, your
make_repeaterreturns another function withnbeing bound to2(this is called a closure). So your code is roughly equivalent to:Which is in turn roughly equivalent to:
Which is in turn roughly equivalent to:
So what you actually do is:
'word' * 2, which results in'wordword'(multiplication of strings is defined by Python as repeating the string the given number of times)5 * 2, which results in10(this should not surprise you)The fact that your lambda function doesn’t care about the type of its argument and dynamically decides at runtime which method of multiplication is correct, is called dynamic typing.