15
votes

This may be simply idiotic, but for me it's a bit confusing:

In [697]: l=[]

In [698]: bool(l)
Out[698]: False

In [699]: l == True
Out[699]: False

In [700]: l == False
Out[700]: False 

In [701]: False == False
Out[701]: True

Why does l==False return False while False == False returns True?

3
Python comparisons are strongly-typed: Objects of different types... never compare equal. That's why l==False fails. - georg

3 Answers

40
votes

You are checking it against the literal value of the boolean False. The same as 'A' == False will not be true.

If you cast it, you'll see the difference:

>>> l = []
>>> l is True
False
>>> l is False
False
>>> l == True
False
>>> l == False
False
>>> bool(l) == False
True

The reason False == False is true is because you are comparing the same objects. It is the same as 2 == 2 or 'A' == 'A'.

The difficulty comes when you see things like if l: and this check never passes. That is because you are checking against the truth value of the item. By convention, all these items will fail a boolean check - that is, their boolean value will be False:

  • None
  • False (obviously)
  • Any empty sequence: '', [], ()
  • Any "zero" value: 0, 0.0, etc.
  • Any empty collection: {} (an empty dict)
  • Anything whose len() returns a 0

These are called "falsey" values. Everything else is "true". Which can lead to some strange things like:

>>> def foo():
...   pass
...
>>> bool(foo)
True

It is also good to note here that methods that don't return an explicit value, always have None as their return type, which leads to this:

>>> def bar():
...   x = 1+1
...
>>> bool(bar)
True
>>> bool(bar())
False
8
votes

An empty list is not the same as False, but False equals False because it's the same object. bool(l) returns False because an empty list is "falsy".

In short, == is not bool() == bool().

For example, [1, 2] == [1, 2, 3] is False, even if the two are "truly".

3
votes

It is because the empty list is not False, it is just "falsy" when converted to a bool, or when evaluated by the an if or while condition (which both evaluate the bool conversion of their condition). See the documentation on Truth Value Testing for more detail.