SilentW
SilentW

Reputation: 233

Boolean evaluation in a lambda

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

Answers (8)

John Fouhy
John Fouhy

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

John Machin
John Machin

Reputation: 82934

isodd = lambda number: (False, True)[number & 1]

Upvotes: 3

Alexander Ljungberg
Alexander Ljungberg

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

Pavel Minaev
Pavel Minaev

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 evaluates C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

Upvotes: 10

fortran
fortran

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

Tomek Kopczuk
Tomek Kopczuk

Reputation: 2113

Yes you can:

isodd = lambda x: x % 2 != 0

Upvotes: 12

Moe
Moe

Reputation: 29733

isodd = lambda number: number %2 != 0

Upvotes: 6

oggy
oggy

Reputation: 3571

lambda num: num % 2 != 0

Upvotes: 12

Related Questions