views:

188

answers:

2

Unless I'm crazy if None not in x and if not None in x are equivalent. Is there a preferred version? I guess None not in is more english-y and therefore more pythonic, but not None in is more like other language syntax. Is there a preferred version?

+12  A: 

They compile to the same 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 the two are equivalent:

x not in s returns the negation of x in s.

As you mention None not in x is more natural English so I prefer to use this.

If you write not y in x it might be unclear whether you meant not (y in x) or (not y) in x. There is no ambiguity if you use not in.

Mark Byers
thanks, didn't know you could compare the bytecode like this.
Uku Loskit
+6  A: 

The expression

not (None in x) 

(parens added for clarity) is an ordinary boolean negation. However,

None not in x

is special syntax added for more readable code (there's no possibility here, nor does it make sense, to use and, or, etc in front of the in). If this special case was added, use it.

Same applies to

foo is not None

vs.

not foo is None

I find the "is not" much clearer to read. As an additional bonus, if the expression is part of a larger boolean expression, the scope of the not is immediately clear.

Ivo van der Wijk
+1 for mentioning scope
Falmarri