# 判斷list是否為空python - 空list python

## 如何檢查列表是否為空? (20)

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

## 檢查列表是否為空的最佳方法

``````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)
1           0 LOAD_GLOBAL              0 (len)
2 BUILD_LIST               0
4 CALL_FUNCTION            1
6 LOAD_CONST               1 (0)
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 {
PyObject_VAR_HEAD
/* 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 = []

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):
# do your stuff.
``````

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

``````a = []
if len(a) == 0:
print("Empty")
else:
print(" Not empty")
``````

``````l = []
if l:
# do your stuff.
``````

``````def empty_list(lst):
if len(lst) ==0:
return false
else:
return all(bool(x) for x in l)
``````

``````if empty_list(lst):
# do your stuff.
``````

``````print('not empty' if a else 'empty')
``````

``````a.pop() if a else None
``````

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

``````if isinstance(a, list) and len(a)==0:
print("Received an empty list")
``````

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

• `None`
• `False`
• 任何數字類型的零，例如， `0j`
• 任何空序列，例如`''``()``[]`
• 任何空映射，例如`{}`
• 用戶定義的類的實例，如果類定義`__bool__()``__len__()`方法，則該方法返回整數零或bool值`False`

``````if not a:
print('"a" is empty!')
``````

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