例如,如果通过以下步骤:

a = []

如何检查a是否为空?


当前回答

if not a:
    print("List is empty")

使用空列表的隐含布尔性是相当Python的。

其他回答

def list_test (L):
    if   L is None  : print('list is None')
    elif not L      : print('list is empty')
    else: print('list has %d elements' % len(L))

list_test(None)
list_test([])
list_test([1,2,3])

有时单独测试无和空是很好的,因为这是两种不同的状态。上述代码产生以下输出:

list is None 
list is empty 
list has 3 elements

虽然没有一件事是假的,但这毫无价值。所以,如果你不想单独测试“无”,你不必这么做。

def list_test2 (L):
    if not L      : print('list is empty')
    else: print('list has %d elements' % len(L))

list_test2(None)
list_test2([])
list_test2([1,2,3])

预期产量

list is empty
list is empty
list has 3 elements

从python3开始,您可以使用

a == []

检查列表是否为空

编辑:这也适用于python2.7。。

我不知道为什么有这么多复杂的答案。这很清楚明了

为什么要检查?

似乎没有人回答过你首先需要测试列表的问题。因为您没有提供额外的上下文,我可以想象,您可能不需要首先执行此检查,但不熟悉Python中的列表处理。

我认为,最Python的方法是根本不检查,而只是处理列表。这样,无论是空的还是满的,它都会做正确的事情。

a = []

for item in a:
    # <Do something with item>

# <The rest of code>

这有利于处理的任何内容,同时不需要对空性进行特定检查。如果a为空,则依赖块将不执行,解释器将进入下一行。

如果确实需要检查数组是否为空:

a = []

if not a:
    # <React to empty list>

# <The rest of code>

足够了。

在真值测试中,空列表本身被认为是错误的(请参见python文档):

a = []
if a:
     print("not empty")

达伦·托马斯的回答:

编辑:反对测试的另一点空列表为False:多态性?你不应该依赖列表是列表。它应该只是像鸭子一样呱呱叫-你怎么样让你的duckCollection呱呱叫当它没有元素时为“False”?

duckCollection应该实现__nonzero_或__len__,因此if-a:将毫无问题地工作。

方法1(首选):

if not a:
   print ("Empty")

方法2:

if len(a) == 0:
   print("Empty")

方法3:

if a == []:
  print ("Empty")