Python Boolean Testing

I tested the list to see if it is empty or not. Usually I use len (list) == 0, and I vaguely remembered how I recently read that the correct way to check if a list is empty, whether it was True or false.

So, I tried the False list, and this returned False. Maybe I suggest using ==? No, it also returned a lie. list is True, returns false, like list == True.

Now I'm confused, so I do a quick google and end with: The best way to check if a list is empty

The main answer:

if not a: print "List is empty" 

So, I search a little more and end up in the python manual, where 4.1:

Any object can be checked for true, for use in an if or while condition, or as an operand of the following Boolean operations. The following values ​​are considered false:

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

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

thanks

+7
source share
4 answers

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

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

When you put something in an if condition, it is its boolean that is used to test if . Therefore, if someList same as if bool(someList) . Similarly, not foo does a boolean, so not [] is True.

+11
source

As others have said, in python bool([]) == False . One thing that is often used by python programmers is that the and and or operators do not return True / False (required). 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 the if is that the condition is evaluated as above, and then python implicitly calls bool as a result. So you can think of it as:

 if condition: 

is the same as:

 if bool(condition): 

regarding python. Similarly for the not operator:

 not condition 

is the same as

 not bool(condition) 
+2
source

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

mylist == False means "is this an object with the name mylist equal to False ?

not mylist mean that an object named mylist is behaving falsely?


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

+1
source

Comparing a list with False , and checking a list of truth or falsity is not exactly the same. An empty list is not False , but behaves like False in a boolean context.

Here's another way to say what might help with this:

 print (bool([]) == False) # will print True print ([] == False) # will print False 
0
source

All Articles