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?


Solution 1:

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"

Solution 2:

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

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

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.

Solution 4:

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

Is fine too

Solution 5:

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.