Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean testing a list in Python

I was testing a list to see if it's empty or not. Normally I use len(list) == 0 and I vaguely remembered reading a little while ago that the correct way to test if a list is empty was whether it was True or false.

So I tried list is False, and that returned False. Maybe I'm suppose to be using == ? Nope, that also returned false. list is True, returned false as did list == True.

Now I'm confused so I do a quick google and end up at: Best way to check if a list is empty

The top answer is:

if not a:
    print "List is empty"

So I search around some more and end up in the python manual where 4.1 states:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

any empty sequence, for example, '', (), [].

Now I'm plain confused. If I test a list as if not list, it works fine. But if an empty list is false, then why can't I just do if list is False or if list == False?

Thanks

like image 733
Jason White Avatar asked Jul 31 '12 02:07

Jason White


3 Answers

An empty list is not False, but when you convert it to a boolean, it converts to False. Likewise for dicts, tuples, strings, etc.:

>>> [] == False
False
>>> bool([]) == False
True
>>> {} == False
False
>>> bool({}) == False
True

When you put something in the condition of an if clause, it is its boolean value that is used for testing the if. That's why if someList is the same as if bool(someList). Likewise, not foo does a boolean not, so not [] equals True.

like image 84
BrenBarn Avatar answered Sep 20 '22 09:09

BrenBarn


As other have said, in python bool([]) == False. One thing that is frequently exploited by python programmers is that the operators and and or don't (necessarily) return True/False. Consider the following:

3 and 4  #returns 4
0 and 8  #returns 0 -- This is short-circuit evaluation
0 or 8   #returns 8
True or 0 #returns True -- This is short-circuit evaluation

[] or False #returns False
False or [] #returns []

What happens in an if statement is that the condition gets evaluated as above and then python implicitly calls bool on the result -- So you can think of it as:

if condition:

is the same thing as:

if bool(condition):

as far as python is concerned. Similarly for the not operator:

not condition

is the same thing as

not bool(condition)
like image 40
mgilson Avatar answered Sep 18 '22 09:09

mgilson


mylist is False means "is the object named mylist exactly the same object as False?"

mylist == False means "is the object named mylist equal to False?

not mylist means "does the object named mylist behave falsily?


None of these are equivalent: 1 is not 1.0 but 1 == 1.0 and [] != False but not [] is True.

like image 39
Katriel Avatar answered Sep 18 '22 09:09

Katriel