Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty list boolean value

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?

like image 910
root Avatar asked Oct 21 '12 11:10

root


People also ask

Is Empty list True or false?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument.

Does an empty list return false?

As an empty list is in fact just a empty collection, it will be converted to a boolean value of False .

Is Empty list equal to none?

Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.

What is the value of empty list in Python?

In Python, empty lists evaluate False , and non-empty lists evaluate True in boolean contexts. Therefore, you can simply treat the list as a predicate returning a Boolean value.


2 Answers

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
like image 137
Burhan Khalid Avatar answered Sep 26 '22 12:09

Burhan Khalid


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".

like image 22
unddoch Avatar answered Sep 24 '22 12:09

unddoch