Reputation: 233
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?
def isodd(number):
if (number%2 == 0):
return False
else:
return True
Elementary, yes. But I'm interested to know...
Upvotes: 11
Views: 53718
Reputation: 42183
Any time you see yourself writing:
if (some condition):
return True
else:
return False
you should replace it with a single line:
return (some condition)
Your function then becomes:
def isodd(number):
return number % 2 != 0
You should be able to see how to get from there to the lambda solution that others have provided.
Upvotes: 3
Reputation: 6362
And if you don't really need a function you can replace it even without a lambda. :)
(number % 2 != 0)
by itself is an expression that evaluates to True or False. Or even plainer,
bool(number % 2)
which you can simplify like so:
if number % 2:
print "Odd!"
else:
print "Even!"
But if that's readable or not is probably in the eye of the beholder.
Upvotes: 16
Reputation: 101565
Others already gave you replies that cover your particular case. In general, however, when you actually need an if
-statement, you can use the conditional expression. For example, if you'd have to return strings "False"
and "True"
rather than boolean values, you could do this:
lambda num: "False" if num%2==0 else "True"
The definition of this expression in Python language reference is as follows:
The expression
x if C else y
first evaluatesC
(notx
); ifC
is true,x
is evaluated and its value is returned; otherwise,y
is evaluated and its value is returned.
Upvotes: 10
Reputation: 76057
And also don't forget that you can emulate complex conditional sentences with simple short-circuit logic, taking advantage that "and" and "or" return some of their ellements (the last one evaluated)... for example, in this case, supposing you'd want to return something different than True or False
lambda x: x%2 and "Odd" or "Even"
Upvotes: 7