Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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.

Browse Categories

...