Empty list is equal to None or not? [duplicate]

雨燕双飞 提交于 2019-11-29 01:00:27

问题


Possible Duplicate:
Why does “[] == False” evaluate to False when “if not []” succeeds?

I am new to python as per ternary operator of python

>>> 'true' if True else 'false'  true
   true

i am expecting for below code output as [] because [] not equal to None

>>> a=[]
>>> a==None
False
>>> a if a else None
None

pleas correct if i am wrong

Thanks hema


回答1:


The empty list, [], is not equal to None.

However, it can evaluate to False--that is to say, its "truthiness" value is False. (See the sources in the comments left on the OP.)

Because of this,

>>> [] == False
False
>>> if []:
...     print "true!"
... else:
...     print "false!"
false!



回答2:


None is the sole instance of the NoneType and is usually used to signify absence of value. What happens in your example is that the empty list, taken in boolean context, evaluates to False, the condition fails, so the else branch gets executed. The interpreter does something along the lines of:

>>> a if a else None
    [] if [] else None
    [] if False else None
None

Here is another useful discussion regarding None: not None test in Python



来源:https://stackoverflow.com/questions/13805882/empty-list-is-equal-to-none-or-not

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