如何检查Python中的列表是否为空?

y2k*_*y2k 98 python list

我正在使用的API可以返回空[]列表.

以下条件语句未按预期工作:

if myList is not None: #not working
    pass

if myList is not []: #not working
    pass
Run Code Online (Sandbox Code Playgroud)

什么会奏效?

Mar*_*arz 172

if not myList:
  print "Nothing here"
Run Code Online (Sandbox Code Playgroud)


shy*_*ent 17

在布尔上下文(例如if some_list:)中,空列表的计算结果为False .


ins*_*get 12

我喜欢Zarembisty的回答.虽然,如果你想更明确,你可以随时做:

if len(my_list) == 0:
    print "my_list is empty"
Run Code Online (Sandbox Code Playgroud)

  • 你可以这样做,但它会违反pep 8,它说: - 对于序列,(字符串,列表,元组),使用空序列为假的事实.是:如果不是seq:如果seq:否:如果len(seq),如果不是len(seq) (32认同)
  • 如果 my_list 为 None,则上述内容将崩溃 (2认同)