### 如何检查数组是否为空？ [重复]

#### [英]How to check if array is not empty? [duplicate]

How to check if the array is not empty? I did this:

``````if not self.table[5] is None:
``````

Is this the right way?

## 8 个解决方案

### #1

45

with `a` as a numpy array, use:

``````if a.size:
print('array is not empty')
``````

(in Python, objects like `[1,2,3]` are called lists, not arrays.)

（在Python中，像[1,2,3]这样的对象被称为列表，而不是数组。）

### #2

44

There's no mention of numpy in the question. If by array you mean list, then if you treat a list as a boolean it will yield True if it has items and False if it's empty.

``````l = []

if l:
print "list has items"

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

### #3

6

``````if self.table:
print 'It is not empty'
``````

Is fine too

### #4

3

`len(self.table)` checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):

len（self.table）检查数组的长度，因此您可以使用if语句来查明列表的长度是否大于0（非空）：

Python 2:

Python 2：

``````if len(self.table) > 0:
#Do code here
``````

Python 3:

Python 3：

``````if(len(self.table) > 0):
#Do code here
``````

It's also possible to use

``````if self.table:
#Execute if self.table is not empty
else:
#Execute if self.table is empty
``````

to see if the list is not empty.

### #5

1

An easy way is to use Boolean expressions:

``````if not self.table[5]:
print('list is empty')
else:
print('list is not empty')
``````

Or you can use another Boolean expression :

``````if self.table[5]==[]:
print('list is empty')
else:
print('list is not empty')
``````

### #6

1

I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:

``````if l:
print "list has items"

elif not l:
print "list is empty"
``````

the error will be:

``````ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
``````

### #7

0

`print(len(a_list))`

As many languages have the `len()` function, in Python this would work for your question. If the output is not `0`, the list is not empty.

### #8

0

If you are talking about Python's actual `array` (available through `import array from array`), then the principle of least astonishment applies and you can check whether it is empty the same way you'd check if a list is empty.

``````from array import array
an_array = array('i') # an array of ints

if an_array:
print("this won't be printed")

an_array.append(3)

if an_array:
print("this will be printed")
``````