Guy Guy - 1 year ago 74
Python Question

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

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
and if so how to do it?


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download