2

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?

4
  • 1
    I dont't see how this could be imporved. However if instead of x and y are going to use large expression you could split this condition into different if-conditions firstly checking for None and then comparing x and y Commented May 8, 2021 at 10:01
  • 1
    you do know where x and y come from right? then you also know if None check is needed or not Commented May 8, 2021 at 10:06
  • 1
    Perhaps: if not None in (x, y) and x > y:. This form can easily be extended to even more variables. Commented May 8, 2021 at 10:06
  • Take a look at this question stackoverflow.com/questions/42360956/… Commented May 8, 2021 at 10:11

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I tend to over use parentheses in my conditionals, I'll streamline it a bit going forward though.
2

Perhaps:

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

Comments

0

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() 

1 Comment

@DarrylG thank you, I just learned a new thing that this code doesn't take zero inot account, edited the answer accordingly. Now it works for 0, -1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.