-1

In the following python code, both lambda functions return the same value, which is x:

x = [2 , 3 , 4 , 5 , 6 , 7 , 8]
print(lambda x: x == 2)

print(lambda x: x if x == 2 else None)

From my understanding, the first lambda function is also an if statement, but I don't quite understand its syntax.

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

The first will return a boolean value (True or False), whereas the second one will return either 2 or None depending on if x == 2 or not.

The first is the same as the following code:

def f(x):
    return (x == 2) # returns either True or False

But the second is the same as this code:

def f(x):
    if (x == 2):
        return (x) 
        # if the code takes this path, x will always be 2 when it's returned
    else:
        return (None) 
        # None is not the same as false

See this post for the difference between None and False

luke
  • 465
  • 1
  • 14
  • 1
    those parentheses are redundant – Matiiss Jul 25 '22 at 21:24
  • 1
    @Matiiss they are redundant, but I left them in the code for clarity since the long form (non lambda) code is intended to be as readable as possible – luke Jul 25 '22 at 21:25
  • 2
    why don't you do `return (x)` and `return (None)` then? they are redundant, they don't help with readability or clarity, they are annoying imo, `if` or `return` is not a function, you don't call it, adding parentheses to a name in Python means calling it, it doesn't happen here because those are keywords – Matiiss Jul 25 '22 at 21:27
  • @Matiiss I've edited to include `return (x)` and `return (none)`. Have a nice day. – luke Jul 25 '22 at 21:29
  • 3
    that's redundancy, redundancy in fact does not help with readability – Matiiss Jul 25 '22 at 21:29
  • See [this post](https://stackoverflow.com/questions/2442088/what-are-some-examples-of-where-using-parentheses-in-a-program-lowers-readabilit/2442151#2442151) about how using parenthesis can help novice readers of python understand the flow of the code – luke Jul 25 '22 at 21:44