0

I feel like this problem is similar to This one

return(lambda x: "Even" if number % 2 == 0 else "Odd")

Of cours I could solve the problem like this:

if number % 2 == 0:
    return("Even")
else: 
    return("Odd")

But I wanted to have a neat one-liner for this. Now I'm stuck, my code returns

at 0x7fb0378fb0d0>

What am I missing?

Community
  • 1
  • 1
Lennart
  • 47
  • 8
  • 5
    Off-topic but I wouldn't really call this "neat", you are hurting your own maintenance (and slight performance) for no real benefit – Sayse Jan 30 '17 at 13:23
  • 2
    `def f(x): return "Even" if x % 2 == 0 else "Odd"` is also a 1-liner, one which is much more readable. I don't see a plausible use-case for this particular lambda. – John Coleman Jan 30 '17 at 13:26
  • Agreed with comments above, generally don't use lambda unless you need an anonymous function (e.g. as a key for sorting) – Chris_Rands Jan 30 '17 at 13:27
  • 2
    So the way I posted the If/Else statement would be better? – Lennart Jan 30 '17 at 13:29
  • Use the exact way of @JohnColeman, you still use `def` but then use ternary operator for a one liner – Chris_Rands Jan 30 '17 at 13:33
  • The if/else is much more readable. In most cases, you will read your code far more often than you write it; optimizing for readability will provide benefits again and again. – George Cummins Jan 30 '17 at 13:49

3 Answers3

2

Lambda returns a function, so you get the address of the function.

Try this:

return ((lambda x: "Even" if x % 2 == 0 else "Odd")(2))

Here you execute the lambda function instead of just return the function itself.

You can assign the lambda function to a variable like this:

func = lambda x: "Even" if x % 2 == 0 else "Odd"

And then call to the function with the relevant parameter:

func(2)
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • Very usefull. Thanks. Why do I need to append the argument instead of integrating it into the lambda statement? – Lennart Jan 30 '17 at 13:25
  • Consider x as the parameter that passed to the lambda, who is that x? you need to call to the lambda with that parameter, in this case it's 2. – omri_saadon Jan 30 '17 at 13:29
2

You shouldn't use a lambda at all. Just do

return 'Even' if number % 2 == 0 else 'Odd'

or

return ('Even', 'Odd')[number % 2]
chepner
  • 497,756
  • 71
  • 530
  • 681
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0

lambda returns function

Try this

f = lambda (x :"Even" if x % 2 == 0 else "Odd")
print f(2)

Hope it helps !

Jay Parikh
  • 2,419
  • 17
  • 13