Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 752
Guy Avatar asked Oct 18 '09 16:10

Guy


People also ask

Can Python lambda take two arguments?

Just like a normal function, a Lambda function can have multiple arguments with one expression.

Can Python lambda have multiple statements?

Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.


1 Answers

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.

like image 155
Robert Rossney Avatar answered Sep 27 '22 22:09

Robert Rossney