2

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.

Community
  • 1
  • 1
dopatraman
  • 13,416
  • 29
  • 90
  • 154
  • Good job asking a better question than the "possible duplicate" question, but the first answer there is pretty awesome. – sarnold Dec 30 '11 at 23:44
  • 1
    I think I'm going to get a mental stack overflow error from recursing into duplicate questions... – Brigand Dec 30 '11 at 23:47
  • See [understanding-lambda-functions in python](http://stackoverflow.com/questions/17833228/understanding-lambda-functions?lq=1) – nawfal Jul 04 '14 at 06:09

2 Answers2

4

As Jake described already, your make_repeater returns another function with n being bound to 2 (this is called a closure). So your code is roughly equivalent to:

twice = lambda s: s * 2

print twice('word')
print twice(5)

Which is in turn roughly equivalent to:

def twice(s):
    return s * 2

print twice('word')
print twice(5)

Which is in turn roughly equivalent to:

print 'word' * 2
print 5 * 2

So what you actually do is:

  • evaluate the expression 'word' * 2, which results in 'wordword' (multiplication of strings is defined by Python as repeating the string the given number of times)
  • evaluate the expression 5 * 2, which results in 10 (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.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
1

The function make_repeater returns another function (the lambda). In your example, the lambda function is assigned the name "twice". The lambda has one argument, "s", and one "static" value, "n" - the "n" is defined when the lambda is created (in this case, it is assigned to "2"). The value for "s" is determined when the lambda is invoked - either "word" or 5. word * 2 = "wordword" and 5 * 2 = 10.

Jake Feasel
  • 16,785
  • 5
  • 53
  • 66