Why is the Boolean value of [None] True and the Boolean value of [] False?

Question:

I was working on a project and stumbled across this weird anomaly, apparently the Boolean value for any list or tuple with an None value is True

Input

print(bool([])) # empty list
print(bool(())) # empty tuple

print(bool([None])) # list with None  
print(bool((None,))) # tuple with None

Output

False
False

True
True

can someone give a brief explanation as to why an list/tuple object with presumably None(null) value will have a Boolean value of True instead of False?

Asked By: Amaan

||

Answers:

A tuple or a list evaluate to False in a boolean context if they’re empty. (None,) and [None] are a tuple/list with 1 element (the element None), hence not empty… therefore they evaluate to True in a boolean context

Answered By: Alberto Garcia
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.