如何检查数组是否为空?

如何检查数组是否为空:

if not self.table[5] is None:

这条路对吗?

267682 次浏览
if self.table:
print 'It is not empty'

Is fine too

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"

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

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

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

Python 2:

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

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.

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()
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.

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