Aloha Ray
Aloha Ray

Reputation: 23

Check if value is not none before comparison

I'm doing a bunch of operations that are basically:

if ((x is not None) and (y is not None)) and x > y:
    do_something

I'm doing this operation on every row of a data table where some of the values are null. Is there a more pythonic way of going about this, without have to check for None each time?

Upvotes: 2

Views: 2122

Answers (3)

Shivam Roy
Shivam Roy

Reputation: 2061

There is not a 'better' way to do it, however if you want to do it in one short line and make it more idiomatic, you could use:

do_something() if x is not None and y is not None and (x>y) else do_something_else()

Upvotes: 0

nnnmmm
nnnmmm

Reputation: 8744

The parentheses are not needed, and None must be capitalized. Otherwise this is basically a good way to do it. Your data table might offer a way of filtering out all rows with None values at once, which would be an improvement.

Upvotes: 3

DarrylG
DarrylG

Reputation: 17156

Perhaps:

if not None in (x, y) and x > y:
    do_something()

Upvotes: 2

Related Questions