Reputation: 139
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
?
Upvotes: 1
Views: 386
Reputation: 21275
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"
Upvotes: 6