Python 3.x – Why is a List Containing an Empty String Truthy?

python-3.x

I have caught something in my work returning a list containing an empty string. I've created an example for simplicity:

big_ol_trickster = [""]
if big_ol_trickster:
    foo()
else:
    print("You can't trick me!")

And this conditional would be satisfied every time. So I've got a question for the python wizards out there: Why is [] == False and "" == False but [""] == True?

Best Answer

Empty lists are Falsey. [""] is not empty. It contains a single element (which happens to be Falsey as well). The Falsey-ness is not evaluated recursively.

To know why is that, look at the implementation of the __bool__ dunder method for the list class. This the method that is called to evaluate truth-value in python. And, yes, you can override it.

[False, False] -> this is also Truthy, it can be counter-intuitive. That's why when you try to use sequences in if conditions you sometimes get "truth-value of sequences can be ambiguous, use any() or all() instead"

Related Question