Is there a way to perform "if" in python's lambda


Question

In python 2.6, I want to do:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it?

thanks

1
314
3/6/2019 4:56:28 PM

Accepted Answer

The syntax you're looking for:

lambda x: True if x % 2 == 0 else False

But you can't use print or raise in a lambda.

590
10/18/2009 4:48:43 PM

why don't you just define a function?

def f(x):
    if x == 2:
        print(x)
    else:
        raise ValueError

there really is no justification to use lambda in this case.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon