Fix Python – Is there a way to perform “if” in python’s lambda?

Question

Asked By – Guy

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?

Now we will see solution for issue: Is there a way to perform “if” in python’s lambda?


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.

This question is answered By – Robert Rossney

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0