admin
admin

Reputation: 11

Why this if return True in Python

>>> if '' is not None: ... print'23333' ... 23333 I think (not None) is True and ('') is False so why it running print?

Upvotes: 0

Views: 69

Answers (2)

elethan
elethan

Reputation: 16993

is and is not test for object identity, i.e., will test if '' and None are the same object, which they are not, so the test returns True in your case.

From the Python documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

To put it another way, although '' and None have the same "truthiness", that is they both evaluate to False if you do bool(None) or bool(''), they to do not refer to the same object.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798486

is not is a single operator, equal to the negation of is. Since '' is None is false, '' is not None is true.

But since is tests identity, not equality, '' is (not None) still won't do what you want.

Upvotes: 2

Related Questions