0

I was going through w3schools' writeup on Python lambdas and came across this example:

def myfunc(n):                    #Statement-1
  return lambda a : a * n         #Statement-2

mydoubler = myfunc(2)             #Statement-3

print(mydoubler(11))              #Statement-4

It says that this code will print 22 as the output.

I am unable to wrap my head around statements-3 and 4 in this code... isn't mydoubler in statement-3 a variable? How can it be used as a function in statement-4?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
SOuser
  • 117
  • 1
  • 9
  • The `myfunc` function returns a lambda function that is stored as `mydoubler`. Functions (incl. lambda functions) can be variables. – Klaus D. Jul 20 '22 at 05:09
  • `mydoubler` is a variable. Its value is the closure (the lambda, pre-loaded with `n`) returned by `myfunc`. `myfunc` could be seen as a variable as well. – Ouroborus Jul 20 '22 at 05:09
  • 1
    A variable is a name that refers to an object, and a function is a kind of object. To get a better understanding, check out [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) by Ned Batchelder. – wjandrea Jul 20 '22 at 05:28
  • @wjandrea Thank you! Please post your comment as an answer. The article and the StackOverflow Q&A you have quoted have helped me understand the code. – SOuser Jul 21 '22 at 05:53
  • 1
    @SOuser Your question is closed under the existing question, so there's no way to add an answer. (BTW, Karl closed it, not me.) But either way, I'm basically just paraphrasing what Martijn said in the linked answer. – wjandrea Jul 21 '22 at 17:11

1 Answers1

2

You can use the substitution model to understand this. The substitution process is as follows:

mydoubler(11)
myfunc(2)(11)
(lambda a:a*2) (11)
11*2
22
Galahad
  • 46
  • 3
  • If anyone reads this answer and doesn't understand what it's talking about, I would sincerely suggest them to first go through writeup mentioned by @wjandrea in the comments to the original question above. – SOuser Jul 22 '22 at 03:36