Lambda instead of "if" statement
Solution 1
Like the others, I'm not sure what you're asking about, but I'm willing to have a guess.
I sometimes use lambdas in a bit of a hacky way processing results from API calls.
Say for example an element of an API call result should be a numeric string which I'd want as an integer, but occasionally it returns something else.
You could defined a lambda to turn a string into an integer if it is comprised of digits:
lambda x: x and x.isdigit() and int(x) or None
This is avoiding an if
statement, but not because of the lambda
, you could do the same as a function:
def f(x):
return x and x.isdigit() and int(x) or None
Update
Less buggy hack, courtesy of Paul McGuire:
lambda x: int(x) if x and x.isdigit() else None
i.e. as int('0')
returns an equivalent of False
the lambda might surprise you by returning None
when you wanted 0
Solution 2
Perhaps you are referring to something like this (Lambda calculus)?
If = lambda test, x, y: test(x, y)
True = lambda x, y: x
False = lambda x, y: y
Which you could use like...
# I guess you have to convert them sometimes... oh well
C = lambda b: [False, True][b]
x = If(C(2 > 3), "Greater", "Less")
print(x)
# "Less"
But now things start to fall apart...
If(C(2 > 3), print("Greater"), print("Less"))
# Invalid syntax unless you use
# from __future__ import print_function
# And if you do, it prints both!
# (Because python has eager evaluation)
# So we could do
True = lambda x, y: x()
False = lambda x, y: y()
# And then
If(C(2 > 3), lambda:print("Greater"), lambda:print("Less"))
# "Less"
So, not so pretty, or useful. But it works.
Solution 3
I might be seriously off, but I'd imagine this means something like:
filter(lambda x: x > 0, list_of_values)
Would return you the elements from list_of_values
which have a value greater than 0.
Solution 4
Following is a little trick inspired by Smalltalk language core, which does not use if statement nor ternary operator, yet working as a conditional execution mechanism. :-)
#!/usr/bin/env python
class ATrue:
def ifThen(self,iftrue): iftrue()
def ifThenElse(self,iftrue,iffalse): return iftrue()
def andThen(self,other): return other()
def orElse(self,other): return self
class AFalse:
def ifThen(self,iftrue): pass
def ifThenElse(self,iftrue,iffalse): return iffalse()
def andThen(self,other): return self
def orElse(self,other): return other()
def echo(x): print x
if __name__=='__main__':
T = ATrue()
F = AFalse()
x = T # True
y = T.andThen(lambda: F) # True and False
z = T.orElse(lambda: F) # True or False
x.ifThenElse( lambda: echo("x is True"), lambda: echo("x if False"))
y.ifThenElse( lambda: echo("y is True"), lambda: echo("y if False"))
z.ifThenElse( lambda: echo("z is True"), lambda: echo("z if False"))
UPDATE: Tidy up some symbols to avoid confusion and make the point clear. And added code to show how short-cut evaluation of logical operators can be implemented.
I159
Updated on June 05, 2022Comments
-
I159 almost 2 years
I've heard that it is possible to substitute an
if
statement by using a lambda.Is this possible in Python? If so, how?
-
Ant over 12 yearswell, you're actually using the if statement :)
-
agf over 12 yearsUm, it is if you put commas between the arguments to the lambda expressions? And maybe show an example of how it would be used? (For my benefit, if noone else's)
-
agf over 12 yearsThis is just the old workaround for having no ternary operator in Python wrapped in a lambda, modern way would be
int(x) if x and x.isdigit() else None
, though that means you don't want to convert '0.0'. -
agf over 12 yearsIt's not an
if
statement, it's a ternary operator. When I googled this topic, that's what the results used (in C#, for example). Python's ternary operator just happens to use the wordif
. -
PaulMcG over 12 yearsAs @agf points out, this old workaround has always carried the risk of doing the wrong thing if one of the terms evaluates successfully to a value that Python treats as a boolean False. If you are going to instruct someone on this hack, at least use a less buggy hack:
lambda x : int(x) if x and x.isdigit() else None
. Now you won't get surprised when x is '0'. -
PaulMcG over 12 yearsWhat if x is "-1"? x.isdigit() returns False here too.
-
MattH over 12 years@Paul, then this wouldn't be a useful function. It was just an example of a guess at what the OP was looking for. Where I use it, the input is a text representation of a positive integer or I don't want it