3

I am relatively new to Python and don't understand the following behavior:

Why does the statement

[] == False 

evaluate to false, eventhough an empty list is falsy?

Here are more examples - in many other cases it seems that the empty list does behave in a falsy way, just not in [] == False...

>>> 0 == False                # what I'd expect
True
>>> not []                    # what I'd expect
True
>>> bool([])                  # what I'd expect
False
>>> [] == True                # what I'd expect
False
>>> [] == False               # unexpected
False
>>> bool([]) == False         # why does it evaluate to True again now?
True
>>> ([]) == (bool([]))        # unexpected
False
>>> (not []) == (not bool([]) # apparently adding 'not' makes it behave as expected again - why?
True


Can somebody please explain this to me? How are these statements internally evaluted?
I have a feeling it might be related to chaining comparisons (see e.g. here), but cannot really understand if that's correct and why.

sam_sc
  • 41
  • 4

1 Answers1

2

Because falsy isn't False. Falsy just means

bool(some_object) is False

So,

>>> bool([]) is False
True
>>> bool({}) is False
True
>>> bool(0) is False
True
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • OK, so what is the difference in this respect between 0 and an empty list? Is it correct to say, that 0 is both falsy and False, whereas an empty list is only falsy but not False? – sam_sc Nov 21 '18 at 12:54
  • 1
    @sam_sc because in Python, due to historical reasons, booleans are subclasses of `int` with exactly two values, True and False, that are equal to 1 and 0 respectively. – juanpa.arrivillaga Nov 21 '18 at 12:56
  • @sam_sc sure, that's a reasonable thing to say. – juanpa.arrivillaga Nov 21 '18 at 12:56
  • OK, that historical explanation makes sense to me. I had a feeling it's something like that. Thanks for your answer, this helps a lot! – sam_sc Nov 21 '18 at 12:59