Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use 'not x' or 'x == 0' to check to see if the result of a modulo operation is zero in python

Tags:

python

I really thought I'd have found something on this, and maybe it's out there and I'm missing it. If that's the case I apologize and I'll close the question.

I'm checking to see if a modulo operation returns a result of zero, and I was wondering which of these is "better" (more pythonic, faster, whatever):

if not count % mod OR if count % mod == 0

I guess I should clarify and say that I have a very good understanding of truthy and falsey values, I just wanted to know if there was a concrete reason to use one over the other. Especially considering this is always going to be a number (otherwise the % operator would throw a TypeError).

like image 623
wpercy Avatar asked Mar 15 '23 07:03

wpercy


1 Answers

In general, the risk with using not x instead of x==0 is that you might match another kind of value that is also falsey (for instance, None or an empty list).

In this case, since x must be a number, it is safe to use not x to mean x==0. Use whichever seems more readable.

To me, the first version looks a little odd, because I expect the results of an arithmetic operation to be treated like a number, so I would prefer the second version. But falseyness is there for convenience, and there are lots of circumstances it makes sense to make use of it.

like image 101
khelwood Avatar answered Apr 08 '23 04:04

khelwood