Empty list boolean value

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

Leave a Comment