# python - set是否为空 - 判断list为空

## 检查列表是否为空的最佳方法

``````a = []
``````

## 简答：

``````if not a:                           # do this!
print('a is an empty list')
``````

## 上诉到权威

PEP 8是Python标准库中Python代码的官方Python风格指南，断言：

``````Yes: if not seq:
if seq:

No: if len(seq):
if not len(seq):
``````

## 说明

``````if len(a) == 0:                     # Don't do this!
print('a is an empty list')
``````

``````if a == []:                         # Don't do this!
print('a is an empty list')
``````

docs （并特别注意包含空列表， `[]` ）：

• 定义为false的常量： `None``False`
• 任何数字类型的零： `0j``Decimal(0)``Fraction(0, 1)`
• 空序列和集合： `''``()``[]``{}``set()``range(0)`

``````if len(a) == 0:                     # Don't do this!
print('a is an empty list')
``````

``````if a == []:                     # Don't do this!
print('a is an empty list')
``````

``````if not a:
print('a is an empty list')
``````

## 做Pythonic通常会在性能方面得到回报：

``````>>> import timeit
>>> min(timeit.repeat(lambda: len([]) == 0, repeat=100))
0.13775854044661884
>>> min(timeit.repeat(lambda: [] == [], repeat=100))
0.0984637276455409
>>> min(timeit.repeat(lambda: not [], repeat=100))
0.07878462291455435
``````

``````>>> min(timeit.repeat(lambda: [], repeat=100))
0.07074015751817342
``````

``````>>> import dis
>>> dis.dis(lambda: len([]) == 0)
2 BUILD_LIST               0
4 CALL_FUNCTION            1
8 COMPARE_OP               2 (==)
10 RETURN_VALUE
``````

``````>>> dis.dis(lambda: [] == [])
1           0 BUILD_LIST               0
2 BUILD_LIST               0
4 COMPARE_OP               2 (==)
6 RETURN_VALUE
``````

“Pythonic”方式是一种更简单，更快速的检查，因为列表的长度缓存在对象实例头中：

``````>>> dis.dis(lambda: not [])
1           0 BUILD_LIST               0
2 UNARY_NOT
4 RETURN_VALUE
``````

## 来自C源和文档的证据

Include/listobject.h的c源代码：

``````typedef struct {
/* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
PyObject **ob_item;

/* ob_item contains space for 'allocated' elements.  The number
* currently in use is ob_size.
* Invariants:
*     0 <= ob_size <= allocated
*     len(list) == ob_size
``````

``````a = []
``````

# 为什么要检查？

``````a = []

for item in a:
<do something with item>

<rest of code>
``````

pythonic的方法是从PEP 8样式指南 （其中Yes表示“推荐”， No表示“不推荐”）：

``````Yes: if not seq:
if seq:

No:  if len(seq):
if not len(seq):
``````

``````l = ["", False, 0, '', [], {}, ()]
if all(bool(x) for x in l):
``````

`````` a = []
try:
print(a[-1])
except IndexError:
print("List is empty")
``````

``````    a = [1,2,3];
print bool(a); # it will return True
a = [];
print bool(a); # it will return False
``````

``````import collections
def is_empty(a):
return not a and isinstance(a, collections.Iterable)
``````

``````>>> is_empty('sss')
False
>>> is_empty(555)
False
>>> is_empty(0)
False
>>> is_empty('')
True
>>> is_empty([3])
False
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(())
True
``````

``````l = []
if l:
``````

``````a = []
if a:
print "not empty"
``````

@Daren Thomas

``````not a
``````

``````if isinstance(a, list) and len(a)==0:
``````

Python代码和Python社区有很强的习惯用法。 遵循这些习语使得使用Python的任何人都可以更轻松地阅读代码。 当你违反这些习语时，这是一个强烈的信号。

``````if not a:
print "list is empty"

if len(a) == 0:
print "list is empty"
``````

``````if not a:
print("The list is empty or null")
``````

``````if a == []:
print "The list is empty."
``````

``````if isinstance(a, (list, some, other, types, i, accept)) and not a:
do_stuff
``````

``````if isinstance(a, numpy.ndarray) and not a.size:
do_stuff
elif isinstance(a, collections.Sized) and not a:
do_stuff
``````

``````elif isinstance(a, (list, tuple)) and not a:
``````

``````elif isinstance(a, (list, tuple)) and not len(a):
``````

``````if len(a) == 0:
print("a is empty")
``````

``````>>> a = []
>>> if a:
...     print "List is not empty";
... else:
...     print "List is empty"
...
List is empty
>>>
>>> a = [1, 4, 9]
>>> if a:
...     print "List is not empty";
... else:
...     print "List is empty"
...
List is not empty
>>>
``````

``````a == []
``````

``````def is_empty(any_structure):
if any_structure:
print('Structure is not empty.')
return True
else:
print('Structure is empty.')
return False
``````

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