-1

I see in this accepted answer to a question about lambda functions in Python, it seems that the parentheses around what was, in the OP's question, a lambda function definition, will cause it to be evaluated. Perhaps standard behavior across languages (as I see similar in Powershell, here)? And this answer about tuples may figure in somehow. It all feels familiar. But can someone provide the link to Python documentation (or succinct text that should be there even if it's not there) explaining why parentheses cause evaluation in Python?

Your answer will help me digest the original answer about lambda functions in list comprehensions.

Community
  • 1
  • 1
talkaboutquality
  • 1,312
  • 2
  • 16
  • 34
  • 2
    *parentheses around ... a lambda function definition, will cause it to be evaluated* - Nope. It was the `(x)` in that answer invoked those lambda functions. – thefourtheye Aug 27 '15 at 15:02
  • 1
    The parentheses around the definition *do not* cause function invocation. They are only there to delimit the lambda definition, as an expression, from other syntax. It is the next set of parentheses, the `(x)` part, that represents *calling* the lambda. – ely Aug 27 '15 at 15:02
  • Updated question title not to be objectively false, thanks to answer. Thanks to commenters, and marking answer accepted. (Or actually, it seems I have to wait 7 minutes before marking an answer accepted. I'll come back soon.) – talkaboutquality Aug 27 '15 at 15:07

1 Answers1

4

No, the parentheses around the lambda do not cause it to be evaluated. They are there to group the expression, to distinguish it from the other parts of the larger expression.

It is the (x) that follows the lambda that does the actual calling:

>>> lambda x: x*x
<function <lambda> at 0x1076b3230>
>>> (lambda x: x*x)
<function <lambda> at 0x1076b32a8>
>>> x = 10
>>> (lambda x: x*x)(x)
100

If you did not use the parentheses, the (x) would be part of the expression encapsulated by the lambda function instead:

>>> lambda x: x*x(x)
<function <lambda> at 0x1076b32a8>

because lambda expressions have the lowest precedence of all Python operators. The relevant documentation about using parentheses is the Parenthesized forms section.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Only after the comments and anser did I see I missed that an actual 'x' (with parentheses around it for function argument syntax) was added. Thanks for the additional information about precedence in Python too! – talkaboutquality Aug 27 '15 at 15:15