Jan 05, 2020

What are differences among "foo == True", "foo is True" and "if foo" in Python?

To check foo really is a boolean and of value True, then is operator is used.

To check true-like value like 1, == is used.

in case of if context: 0, False, None, Empty String, Empty containers (List, Tuple, Dictionaries..etc.) are considered as False.


1 == True
True

1 is True
False

2 == True
False

2 is True
False

True if 2 else False
True

lst = ['item']
lst == True
False

lst is True
False

lst == False
False

True if lst else False
True

0 == False
True

None == False
False

True if None else False
False

'' == False
False

True if '' else False
False

As a rule of thumb, you should always use is with the built-in constants True, False and None.

Enjoy Python!