"x == None" vs "x is None"

Peter Otten __peter__ at web.de
Sun Jan 17 06:26:45 EST 2016


Ulli Horlacher wrote:

> Chris Angelico <rosuav at gmail.com> wrote:
>> On Sun, Jan 17, 2016 at 8:51 PM, Ulli Horlacher
>> <framstag at rus.uni-stuttgart.de> wrote:
>> > I have seen at several places "x == None" and "x is None" within
>> > if-statements.
>> > What is the difference?
>> > Which term should I prefer and why?
>> 
>> tl;dr: Prefer "x is None" as a check.
> 
> And for the negation?
> "if not x is None" or "if x is not None"
> 
> I have seen the last one several times, but i do not understand it,
> because:
> 
>>>> x=0
>>>> x is not None
> True
>>>> not None
> True
>>>> x is True
> False

- "is" has higher precedence than "not"
- "is not" is an operator in its own right. 

So the evaluation is

not (x is None)
x (is not) None

https://docs.python.org/dev/library/stdtypes.html#comparisons
https://docs.python.org/dev/reference/expressions.html#operator-precedence




More information about the Python-list mailing list