Why is a list containing an empty string truthy?

后端 未结 1 1297
粉色の甜心
粉色の甜心 2021-01-24 05:48

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_tric         


        
相关标签:
1条回答
  • 2021-01-24 06:06

    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"

    0 讨论(0)
提交回复
热议问题