How does a lambda function get it's value?












1















Reviewing the W3Schools Python tutorial, I am puzzled by their example of lambda.



Where on earth is the value for variable "a" coming from? Sure, "a" is the lambda - but where is it getting a value from?



def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))


If I call print(myfunc(3)) on it's own, I get an error. The function only works if the function is CALLED by another function. How does lambda a know any of this?



I fear I am missing something very fundamental about lambda functions.










share|improve this question























  • It is a parameter. just like if you did def f(a): return a * n. And print(myfunc(3)) does not produce an error, prints the return value of myfunc, which is a functions

    – juanpa.arrivillaga
    Jan 2 at 17:10






  • 2





    I get "<function myfunc.<locals>.<lambda> at 0x7fcda75e8d08>" as the result of print(myfunc(3)). This is not an error but a (not very beginner friendly) textual representation of a function. Compare print(print), which gives me "<built-in function print>"

    – Caleth
    Jan 2 at 17:35


















1















Reviewing the W3Schools Python tutorial, I am puzzled by their example of lambda.



Where on earth is the value for variable "a" coming from? Sure, "a" is the lambda - but where is it getting a value from?



def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))


If I call print(myfunc(3)) on it's own, I get an error. The function only works if the function is CALLED by another function. How does lambda a know any of this?



I fear I am missing something very fundamental about lambda functions.










share|improve this question























  • It is a parameter. just like if you did def f(a): return a * n. And print(myfunc(3)) does not produce an error, prints the return value of myfunc, which is a functions

    – juanpa.arrivillaga
    Jan 2 at 17:10






  • 2





    I get "<function myfunc.<locals>.<lambda> at 0x7fcda75e8d08>" as the result of print(myfunc(3)). This is not an error but a (not very beginner friendly) textual representation of a function. Compare print(print), which gives me "<built-in function print>"

    – Caleth
    Jan 2 at 17:35
















1












1








1


1






Reviewing the W3Schools Python tutorial, I am puzzled by their example of lambda.



Where on earth is the value for variable "a" coming from? Sure, "a" is the lambda - but where is it getting a value from?



def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))


If I call print(myfunc(3)) on it's own, I get an error. The function only works if the function is CALLED by another function. How does lambda a know any of this?



I fear I am missing something very fundamental about lambda functions.










share|improve this question














Reviewing the W3Schools Python tutorial, I am puzzled by their example of lambda.



Where on earth is the value for variable "a" coming from? Sure, "a" is the lambda - but where is it getting a value from?



def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))


If I call print(myfunc(3)) on it's own, I get an error. The function only works if the function is CALLED by another function. How does lambda a know any of this?



I fear I am missing something very fundamental about lambda functions.







python lambda






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 17:06









frozenjimfrozenjim

49049




49049













  • It is a parameter. just like if you did def f(a): return a * n. And print(myfunc(3)) does not produce an error, prints the return value of myfunc, which is a functions

    – juanpa.arrivillaga
    Jan 2 at 17:10






  • 2





    I get "<function myfunc.<locals>.<lambda> at 0x7fcda75e8d08>" as the result of print(myfunc(3)). This is not an error but a (not very beginner friendly) textual representation of a function. Compare print(print), which gives me "<built-in function print>"

    – Caleth
    Jan 2 at 17:35





















  • It is a parameter. just like if you did def f(a): return a * n. And print(myfunc(3)) does not produce an error, prints the return value of myfunc, which is a functions

    – juanpa.arrivillaga
    Jan 2 at 17:10






  • 2





    I get "<function myfunc.<locals>.<lambda> at 0x7fcda75e8d08>" as the result of print(myfunc(3)). This is not an error but a (not very beginner friendly) textual representation of a function. Compare print(print), which gives me "<built-in function print>"

    – Caleth
    Jan 2 at 17:35



















It is a parameter. just like if you did def f(a): return a * n. And print(myfunc(3)) does not produce an error, prints the return value of myfunc, which is a functions

– juanpa.arrivillaga
Jan 2 at 17:10





It is a parameter. just like if you did def f(a): return a * n. And print(myfunc(3)) does not produce an error, prints the return value of myfunc, which is a functions

– juanpa.arrivillaga
Jan 2 at 17:10




2




2





I get "<function myfunc.<locals>.<lambda> at 0x7fcda75e8d08>" as the result of print(myfunc(3)). This is not an error but a (not very beginner friendly) textual representation of a function. Compare print(print), which gives me "<built-in function print>"

– Caleth
Jan 2 at 17:35







I get "<function myfunc.<locals>.<lambda> at 0x7fcda75e8d08>" as the result of print(myfunc(3)). This is not an error but a (not very beginner friendly) textual representation of a function. Compare print(print), which gives me "<built-in function print>"

– Caleth
Jan 2 at 17:35














3 Answers
3






active

oldest

votes


















1














a in your example is assigned the value 11.



Think of the definition of a lambda function as "when given an input, return this". You can name the input anything, so let's call it x. lambda x : x + 1 means "given an input that we'll call x : return x + 1".



You have an extra layer of a function returning a lambda, but if we break it down, the purpose of myfunc is to dynamically generate a lambda function. When you call myfunc(3), what you now have in your hands is a lambda function that looks like this: lambda a : a * 3. This is what the variable mytripler contains. If you print(mytripler), you see something like this: <function myfunc.<locals>.<lambda> at 0x...>, which tells you that it's some lambda function. mytripler contains a function, not a value.



What does this lambda function do? It says "given one input parameter which we'll call a : return a * 3".



What do you do with functions? You call them! And send any parameters along with the call. How many parameters does our lambda function take? However many variables precede the colon in the lambda function definition, in this case one: a. And so we call the lambda stored in mytripler by sending it one parameter: mytripler(11). 11 is the input to the lambda function, which is first assigned to a and returns a * 3 -> 33.



You could have a lambda that takes 2 inputs that we'll call x and y:
adder = lambda x, y : x + y
What does this lambda do? It says "given 2 inputs that we'll call x and y : return their sum". How do you call it? You have to call adder with two parameters: adder(2,3) returns 5. 2 is assigned to x, 3 is assigned to y and the function returns their sum.



What if we call adder(1)?
TypeError: <lambda>() missing 1 required positional argument: 'y'



From this you can see that Python knows how many input parameters the lambda function expects from its definition and cannot work without first getting all the parameters it needs.






share|improve this answer
























  • I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

    – frozenjim
    Jan 20 at 16:00













  • Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

    – Steven
    Jan 24 at 13:45











  • Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

    – frozenjim
    Jan 24 at 13:48



















5














Lambdas are just shorthands for full declarations. That makes your example functionally identical to this:



def myfunc(n):
def inner(a):
return a * n
return inner


The lambda is a function, and when you call it, you provide it an argument (a in this example).






share|improve this answer































    3














    What myfunc(3) does is that it assigns 3 to n and then this value is used in the lambda expression. So the expression becomes 3*a. Your lambda function has an independent variable a. When you return lambda a : a * n your mytripler is now acting as an object (function) whose argument is a and the action is to compute a*3. So finally when you call



    mytripler(11)


    you are assigning 11 to your independent variable a thereby getting 33






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010380%2fhow-does-a-lambda-function-get-its-value%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      a in your example is assigned the value 11.



      Think of the definition of a lambda function as "when given an input, return this". You can name the input anything, so let's call it x. lambda x : x + 1 means "given an input that we'll call x : return x + 1".



      You have an extra layer of a function returning a lambda, but if we break it down, the purpose of myfunc is to dynamically generate a lambda function. When you call myfunc(3), what you now have in your hands is a lambda function that looks like this: lambda a : a * 3. This is what the variable mytripler contains. If you print(mytripler), you see something like this: <function myfunc.<locals>.<lambda> at 0x...>, which tells you that it's some lambda function. mytripler contains a function, not a value.



      What does this lambda function do? It says "given one input parameter which we'll call a : return a * 3".



      What do you do with functions? You call them! And send any parameters along with the call. How many parameters does our lambda function take? However many variables precede the colon in the lambda function definition, in this case one: a. And so we call the lambda stored in mytripler by sending it one parameter: mytripler(11). 11 is the input to the lambda function, which is first assigned to a and returns a * 3 -> 33.



      You could have a lambda that takes 2 inputs that we'll call x and y:
      adder = lambda x, y : x + y
      What does this lambda do? It says "given 2 inputs that we'll call x and y : return their sum". How do you call it? You have to call adder with two parameters: adder(2,3) returns 5. 2 is assigned to x, 3 is assigned to y and the function returns their sum.



      What if we call adder(1)?
      TypeError: <lambda>() missing 1 required positional argument: 'y'



      From this you can see that Python knows how many input parameters the lambda function expects from its definition and cannot work without first getting all the parameters it needs.






      share|improve this answer
























      • I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

        – frozenjim
        Jan 20 at 16:00













      • Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

        – Steven
        Jan 24 at 13:45











      • Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

        – frozenjim
        Jan 24 at 13:48
















      1














      a in your example is assigned the value 11.



      Think of the definition of a lambda function as "when given an input, return this". You can name the input anything, so let's call it x. lambda x : x + 1 means "given an input that we'll call x : return x + 1".



      You have an extra layer of a function returning a lambda, but if we break it down, the purpose of myfunc is to dynamically generate a lambda function. When you call myfunc(3), what you now have in your hands is a lambda function that looks like this: lambda a : a * 3. This is what the variable mytripler contains. If you print(mytripler), you see something like this: <function myfunc.<locals>.<lambda> at 0x...>, which tells you that it's some lambda function. mytripler contains a function, not a value.



      What does this lambda function do? It says "given one input parameter which we'll call a : return a * 3".



      What do you do with functions? You call them! And send any parameters along with the call. How many parameters does our lambda function take? However many variables precede the colon in the lambda function definition, in this case one: a. And so we call the lambda stored in mytripler by sending it one parameter: mytripler(11). 11 is the input to the lambda function, which is first assigned to a and returns a * 3 -> 33.



      You could have a lambda that takes 2 inputs that we'll call x and y:
      adder = lambda x, y : x + y
      What does this lambda do? It says "given 2 inputs that we'll call x and y : return their sum". How do you call it? You have to call adder with two parameters: adder(2,3) returns 5. 2 is assigned to x, 3 is assigned to y and the function returns their sum.



      What if we call adder(1)?
      TypeError: <lambda>() missing 1 required positional argument: 'y'



      From this you can see that Python knows how many input parameters the lambda function expects from its definition and cannot work without first getting all the parameters it needs.






      share|improve this answer
























      • I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

        – frozenjim
        Jan 20 at 16:00













      • Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

        – Steven
        Jan 24 at 13:45











      • Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

        – frozenjim
        Jan 24 at 13:48














      1












      1








      1







      a in your example is assigned the value 11.



      Think of the definition of a lambda function as "when given an input, return this". You can name the input anything, so let's call it x. lambda x : x + 1 means "given an input that we'll call x : return x + 1".



      You have an extra layer of a function returning a lambda, but if we break it down, the purpose of myfunc is to dynamically generate a lambda function. When you call myfunc(3), what you now have in your hands is a lambda function that looks like this: lambda a : a * 3. This is what the variable mytripler contains. If you print(mytripler), you see something like this: <function myfunc.<locals>.<lambda> at 0x...>, which tells you that it's some lambda function. mytripler contains a function, not a value.



      What does this lambda function do? It says "given one input parameter which we'll call a : return a * 3".



      What do you do with functions? You call them! And send any parameters along with the call. How many parameters does our lambda function take? However many variables precede the colon in the lambda function definition, in this case one: a. And so we call the lambda stored in mytripler by sending it one parameter: mytripler(11). 11 is the input to the lambda function, which is first assigned to a and returns a * 3 -> 33.



      You could have a lambda that takes 2 inputs that we'll call x and y:
      adder = lambda x, y : x + y
      What does this lambda do? It says "given 2 inputs that we'll call x and y : return their sum". How do you call it? You have to call adder with two parameters: adder(2,3) returns 5. 2 is assigned to x, 3 is assigned to y and the function returns their sum.



      What if we call adder(1)?
      TypeError: <lambda>() missing 1 required positional argument: 'y'



      From this you can see that Python knows how many input parameters the lambda function expects from its definition and cannot work without first getting all the parameters it needs.






      share|improve this answer













      a in your example is assigned the value 11.



      Think of the definition of a lambda function as "when given an input, return this". You can name the input anything, so let's call it x. lambda x : x + 1 means "given an input that we'll call x : return x + 1".



      You have an extra layer of a function returning a lambda, but if we break it down, the purpose of myfunc is to dynamically generate a lambda function. When you call myfunc(3), what you now have in your hands is a lambda function that looks like this: lambda a : a * 3. This is what the variable mytripler contains. If you print(mytripler), you see something like this: <function myfunc.<locals>.<lambda> at 0x...>, which tells you that it's some lambda function. mytripler contains a function, not a value.



      What does this lambda function do? It says "given one input parameter which we'll call a : return a * 3".



      What do you do with functions? You call them! And send any parameters along with the call. How many parameters does our lambda function take? However many variables precede the colon in the lambda function definition, in this case one: a. And so we call the lambda stored in mytripler by sending it one parameter: mytripler(11). 11 is the input to the lambda function, which is first assigned to a and returns a * 3 -> 33.



      You could have a lambda that takes 2 inputs that we'll call x and y:
      adder = lambda x, y : x + y
      What does this lambda do? It says "given 2 inputs that we'll call x and y : return their sum". How do you call it? You have to call adder with two parameters: adder(2,3) returns 5. 2 is assigned to x, 3 is assigned to y and the function returns their sum.



      What if we call adder(1)?
      TypeError: <lambda>() missing 1 required positional argument: 'y'



      From this you can see that Python knows how many input parameters the lambda function expects from its definition and cannot work without first getting all the parameters it needs.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 2 at 19:11









      StevenSteven

      463310




      463310













      • I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

        – frozenjim
        Jan 20 at 16:00













      • Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

        – Steven
        Jan 24 at 13:45











      • Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

        – frozenjim
        Jan 24 at 13:48



















      • I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

        – frozenjim
        Jan 20 at 16:00













      • Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

        – Steven
        Jan 24 at 13:45











      • Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

        – frozenjim
        Jan 24 at 13:48

















      I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

      – frozenjim
      Jan 20 at 16:00







      I get it... I hate it. This is the best way to generate spaghetti code that I have ever seen. Thanks for the explanation.

      – frozenjim
      Jan 20 at 16:00















      Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

      – Steven
      Jan 24 at 13:45





      Haha, I think you might hate it because you encountered it as an abstract tutorial example, so its benefit isn't obvious. I suspect that given the right opportunity, when a lambda shows itself as a nice, compact shorthand that spares you the trouble of defining a one-liner function just so you can call it once, you might start to like them.

      – Steven
      Jan 24 at 13:45













      Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

      – frozenjim
      Jan 24 at 13:48





      Yeah, I do see how it could have use in defining on-the-fly functionality. In the tutorial This example is clearly not clear (nowhere is the explanation of where “a” comes from ) not, as you point out, useful.

      – frozenjim
      Jan 24 at 13:48













      5














      Lambdas are just shorthands for full declarations. That makes your example functionally identical to this:



      def myfunc(n):
      def inner(a):
      return a * n
      return inner


      The lambda is a function, and when you call it, you provide it an argument (a in this example).






      share|improve this answer




























        5














        Lambdas are just shorthands for full declarations. That makes your example functionally identical to this:



        def myfunc(n):
        def inner(a):
        return a * n
        return inner


        The lambda is a function, and when you call it, you provide it an argument (a in this example).






        share|improve this answer


























          5












          5








          5







          Lambdas are just shorthands for full declarations. That makes your example functionally identical to this:



          def myfunc(n):
          def inner(a):
          return a * n
          return inner


          The lambda is a function, and when you call it, you provide it an argument (a in this example).






          share|improve this answer













          Lambdas are just shorthands for full declarations. That makes your example functionally identical to this:



          def myfunc(n):
          def inner(a):
          return a * n
          return inner


          The lambda is a function, and when you call it, you provide it an argument (a in this example).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 17:10









          g.d.d.cg.d.d.c

          34.7k77194




          34.7k77194























              3














              What myfunc(3) does is that it assigns 3 to n and then this value is used in the lambda expression. So the expression becomes 3*a. Your lambda function has an independent variable a. When you return lambda a : a * n your mytripler is now acting as an object (function) whose argument is a and the action is to compute a*3. So finally when you call



              mytripler(11)


              you are assigning 11 to your independent variable a thereby getting 33






              share|improve this answer




























                3














                What myfunc(3) does is that it assigns 3 to n and then this value is used in the lambda expression. So the expression becomes 3*a. Your lambda function has an independent variable a. When you return lambda a : a * n your mytripler is now acting as an object (function) whose argument is a and the action is to compute a*3. So finally when you call



                mytripler(11)


                you are assigning 11 to your independent variable a thereby getting 33






                share|improve this answer


























                  3












                  3








                  3







                  What myfunc(3) does is that it assigns 3 to n and then this value is used in the lambda expression. So the expression becomes 3*a. Your lambda function has an independent variable a. When you return lambda a : a * n your mytripler is now acting as an object (function) whose argument is a and the action is to compute a*3. So finally when you call



                  mytripler(11)


                  you are assigning 11 to your independent variable a thereby getting 33






                  share|improve this answer













                  What myfunc(3) does is that it assigns 3 to n and then this value is used in the lambda expression. So the expression becomes 3*a. Your lambda function has an independent variable a. When you return lambda a : a * n your mytripler is now acting as an object (function) whose argument is a and the action is to compute a*3. So finally when you call



                  mytripler(11)


                  you are assigning 11 to your independent variable a thereby getting 33







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 2 at 17:10









                  BazingaaBazingaa

                  16.8k21330




                  16.8k21330






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010380%2fhow-does-a-lambda-function-get-its-value%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas

                      Can't read property showImagePicker of undefined in react native iOS