Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour of `not` operator with python list

When I'm trying to check whether a list is empty or not using python's not operator it is behaving in a weird manner.

I tried using the not operator with a list to check whether it is empty or not.

>>> a = []
>>> not (a)
True
>>> not (a) == True
True
>>> not (a) == False
True
>>> True == False
False

The expected output for not (a) == False should be False.

like image 221
Aadil Srivastava Avatar asked Sep 19 '19 19:09

Aadil Srivastava


2 Answers

== has higher precedence than not. not (a) == False is parsed as not (a == False).

like image 79
John Kugelman Avatar answered Oct 02 '22 04:10

John Kugelman


This is working as expected. Parenthesis added below to clarify how this is being executed:

not (a == True)
# True
not (a == False)
# True

An empty list, a = [], evaluates to False in boolean expressions, but it does not equal False or True. Your expressions in the middle are testing whether it is equal to False or True, so they both evaluate to False, and not False is True.

You can add parenthesis like below to get what you expect:

(not a) == True
# True
(not a) == False
# False
like image 31
Engineero Avatar answered Oct 02 '22 04:10

Engineero