1

I'm a little bit scared about the "is not" operator and the possibility that "is not X" is interpreted when "is (not X)" was intended. Do exist some expressions A and B such that:

A is not B

is different from

A is (not B)

?

addendum. Is it considered good practice to use this operator? Should't not (A is B) be preferred?

Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64
  • possible duplicate of [Python "is" statement: what is happening?](http://stackoverflow.com/questions/3718513/python-is-statement-what-is-happening) – Rafael Barros Jul 07 '14 at 15:53
  • In some cases, `not B` will be an error, if `B` can't be used as an implicit Boolean. – kindall Jul 07 '14 at 15:53

2 Answers2

10

They're definitely different. The latter case evaluates not X in a boolean context first and then checks to see if the two objects are the same object (either True or False).

Consider:

False is not []

This expression is trivially True since False and [] are quite clearly different objects. 1

vs.

False is (not [])

This expression is False since not [] evalutes to True and False and True are different objects.

Of course, this is just one example. It gets even easier to find examples if you don't use False and True explicitly as the second expression will always be False and the first expression will (almost) always be True...

3 is not 0   # True
3 is (not 0)   # False

1Note that is not is a single operator in the same vein as not in.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 2
    Same result for me in Python 2.7 and Python 3.3. Use `False is not []` to see a difference. – Matthias Jul 07 '14 at 15:57
  • @Matthias -- Thanks. Early morning brain fog I guess. I'm always surprised by the number of upvotes you can pull in even with a wrong answer :-) – mgilson Jul 07 '14 at 16:03
7

Yes:

A = 0
B = 1

Try it and you'll be really scared:

>>> A = 0
>>> B = 1
>>> A is not B
True
>>> A is (not B)
False
Maroun
  • 94,125
  • 30
  • 188
  • 241