如何检查列表是否为空?

2024-04-24 00:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果通过了以下操作:

a = []

如何检查a是否为空?


3条回答

我更愿意明确地说:

if len(li) == 0:
    print('the list is empty')

这样就可以100%地确定li是一个序列(列表),我们想测试它的大小。我对if not li: ...的问题是,它给人的错误印象是li是一个布尔变量。

python方法是从PEP 8 style guide(其中表示“推荐”,而表示“不推荐”):

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):
if not a:
  print("List is empty")

使用空的listimplicit booleanness是相当的python。

相关问题 更多 >