0 votes
1 view
in Python by (14.5k points)

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 Answer

0 votes
by (32.1k points)

Yes, you can perform “if” in python's lambda,  the syntax for that is as follows:-

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

One important point to note here is that you can't use print or raise in a lambda.

...