Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading