Is there a way to perform "if" in python's lambda?
Question:
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?
Answers:
Lambdas in Python are fairly restrictive with regard to what you’re allowed to use. Specifically, you can’t have any keywords (except for operators like and
, not
, or
, etc) in their body.
So, there’s no way you could use a lambda for your example (because you can’t use raise
), but if you’re willing to concede on that… You could use:
f = lambda x: x == 2 and x or None
why don’t you just define a function?
def f(x):
if x == 2:
print(x)
else:
raise ValueError
there really is no justification to use lambda in this case.
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.
You can easily raise an exception in a lambda, if that’s what you really want to do.
def Raise(exception):
raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don’t think this is inherently evil, though–I consider the “y if x else z” syntax itself worse–just make sure you’re not trying to stuff too much into a lambda body.
Probably the worst python line I’ve written so far:
f = lambda x: sys.stdout.write(["2n",][2*(x==2)-2])
If x == 2 you print,
if x != 2 you raise.
note you can use several else…if statements in your lambda definition:
f = lambda x: 1 if x>0 else 0 if x ==0 else -1
If you still want to print you can import future module
from __future__ import print_function
f = lambda x: print(x) if x%2 == 0 else False
You can also use Logical Operators to have something like a Conditional
func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse
You can see more about Logical Operators here
Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.
a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
what you need exactly is
def fun():
raise Exception()
f = lambda x:print x if x==2 else fun()
now call the function the way you need
f(2)
f(3)
This snippet should help you:
x = lambda age: 'Older' if age > 30 else 'Younger'
print(x(40))
An easy way to perform an if in lambda is by using list comprehension.
You can’t raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:
f = lambda x: print(x) if x==2 else print("exception")
Another example:
return 1 if M otherwise 0
f = lambda x: 1 if x=="M" else 0
Hope this will help a little
you can resolve this problem in the following way
f = lambda x: x==2
if f(3):
print("do logic")
else:
print("another logic")
Here’s the solution if you use Python 3.x!
>>> f = lambda x: print(x) if x == 2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>>
the solution for the given scenerio is:
f = lambda x : x if x == 2 else print("number is not 2")
f(30) # number is not 2
f(2) #2
it might be worth considering np.where
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?
Lambdas in Python are fairly restrictive with regard to what you’re allowed to use. Specifically, you can’t have any keywords (except for operators like and
, not
, or
, etc) in their body.
So, there’s no way you could use a lambda for your example (because you can’t use raise
), but if you’re willing to concede on that… You could use:
f = lambda x: x == 2 and x or None
why don’t you just define a function?
def f(x):
if x == 2:
print(x)
else:
raise ValueError
there really is no justification to use lambda in this case.
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.
You can easily raise an exception in a lambda, if that’s what you really want to do.
def Raise(exception):
raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don’t think this is inherently evil, though–I consider the “y if x else z” syntax itself worse–just make sure you’re not trying to stuff too much into a lambda body.
Probably the worst python line I’ve written so far:
f = lambda x: sys.stdout.write(["2n",][2*(x==2)-2])
If x == 2 you print,
if x != 2 you raise.
note you can use several else…if statements in your lambda definition:
f = lambda x: 1 if x>0 else 0 if x ==0 else -1
If you still want to print you can import future module
from __future__ import print_function
f = lambda x: print(x) if x%2 == 0 else False
You can also use Logical Operators to have something like a Conditional
func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse
You can see more about Logical Operators here
Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.
a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
what you need exactly is
def fun():
raise Exception()
f = lambda x:print x if x==2 else fun()
now call the function the way you need
f(2)
f(3)
This snippet should help you:
x = lambda age: 'Older' if age > 30 else 'Younger'
print(x(40))
An easy way to perform an if in lambda is by using list comprehension.
You can’t raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:
f = lambda x: print(x) if x==2 else print("exception")
Another example:
return 1 if M otherwise 0
f = lambda x: 1 if x=="M" else 0
Hope this will help a little
you can resolve this problem in the following way
f = lambda x: x==2
if f(3):
print("do logic")
else:
print("another logic")
Here’s the solution if you use Python 3.x!
>>> f = lambda x: print(x) if x == 2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>>
the solution for the given scenerio is:
f = lambda x : x if x == 2 else print("number is not 2")
f(30) # number is not 2
f(2) #2
it might be worth considering np.where