"Not in either vs or None in

If I'm not crazy if None not in x and if not None in x equivalent. Is there a preferred version? I think None not in more English-y and therefore more pythonic, but not None in more like the syntax of another language. Is there a preferred version?

+6
python syntax logic
source share
2 answers

They are compiled into a single bytecode, so yes, they are equivalent.

 >>> import dis >>> dis.dis(lambda: None not in x) 1 0 LOAD_CONST 0 (None) 3 LOAD_GLOBAL 1 (x) 6 COMPARE_OP 7 (not in) 9 RETURN_VALUE >>> dis.dis(lambda: not None in x) 1 0 LOAD_CONST 0 (None) 3 LOAD_GLOBAL 1 (x) 6 COMPARE_OP 7 (not in) 9 RETURN_VALUE 

The documentation also makes it clear that these two equivalents:

x not in s returns negation x in s .

As you say, None not in x more natural English, so I prefer to use it.

If you write not y in x , it may not be clear if you have the value not (y in x) or (not y) in x . There is no ambiguity if you use not in .

+14
source share

Expression

 not (None in x) 

(partners added for clarity) - this is the usual Boolean negation. Nevertheless,

 None not in x 

special syntax was added for more readable code (there is no possibility here and it makes no sense to use and, or, etc. before entering). If this special case has been added, use it.

The same applies to

 foo is not None 

against.

 not foo is None 

I find that β€œreading” is not so clear. As an added bonus, if an expression is part of a larger logical expression, the scope does not immediately become clear.

+7
source share

All Articles