Python 空列表是否等于 None ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13805882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:39:24  来源:igfitidea点击:

Empty list is equal to None or not?

pythonpython-3.xpython-2.7ironpython

提问by user1559873

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

可能的重复:
当“if not []”成功时,为什么“[] == False”评估为False?

I am new to python as per ternary operator of python

根据python的三元运算符,我是python的新手

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

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

我期待以下代码输出为 [] 因为 [] 不等于 None

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

pleas correct if i am wrong

如果我错了,请纠正

Thanks hema

谢谢盒马

采纳答案by jdotjdot

The empty list, [], is notequal to None.

空单,[]不是等于None

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

但是,它可以求值为False——也就是说,它的“真实性”值为False。(请参阅 OP 上留下的评论中的来源。)

Because of this,

因为这,

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

回答by ank

Noneis the sole instance of the NoneTypeand 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:

None是 的唯一实例,NoneType通常用于表示没有值。在您的示例中发生的情况是,在布尔上下文中采用的空列表评估为False,条件失败,因此执行 else 分支。解释器做一些事情:

>>> 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

这是另一个关于Nonenot None test in Python 的有用讨论