Weird behaviour of `not` operator with python list

混江龙づ霸主 提交于 2021-02-05 05:01:44

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/58017682/weird-behaviour-of-not-operator-with-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!