How do I check if a list is empty?

For example, if passed the following:

a = []

How do I check to see if a is empty?


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

使用空列表的隐式布尔型是相当pythonic。


The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):

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

I prefer it explicitly:

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

This way it's 100% clear that li is a sequence (list) and we want to test its size. My problem with if not li: ... is that it gives the false impression that li is a boolean variable.

链接地址: http://www.djcxy.com/p/510.html

上一篇: 在int中枚举枚举在C#中枚举

下一篇: 如何检查列表是否为空?