For example, if passed the following:
a = 
How do I check to see if
a is empty?
How to check if a list is empty in Python?
This can be done using this code snippet:
if not a: print("List is empty")
Using the implicit booleanness of the empty
list is quite pythonic.
Read more on how to sort a list in Python.
The pythonic way to do it is from the PEP 8 style guide.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
Python program to check whether a list is empty or not:
I prefer it explicitly:
if len(li) == 0: print('the list is empty')
This way it’s 100% clear that li is a sequence (list) and we want to test its size. My problem with if not li: … is that it gives a false impression that
li is a boolean variable.
Test empty array in Python- Answer #3:
This is the first google hit for “python test empty array” and similar queries, plus other people seem to be generalizing the question beyond just lists, so I thought I’d add a caveat for a different type of sequence that a lot of people might use.
Other methods don’t work for NumPy arrays
You need to be careful with NumPy arrays, because other methods that work fine for
lists or other standard containers fail for NumPy arrays. I explain why below, but in short, the preferred method is to use
The “pythonic” way doesn’t work: Part 1
The “pythonic” way fails with NumPy arrays because NumPy tries to cast the array to an array of
if x tries to evaluate all of those
bools at once for some kind of aggregate truth value. But this doesn’t make any sense, so you get a
>>> x = numpy.array([0,1]) >>> if x: print("x") ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The “pythonic” way doesn’t work: Part 2
But at least the case above tells you that it failed. If you happen to have a NumPy array with exactly one element, the
if statement will “work”, in the sense that you don’t get an error. However, if that one element happens to be
False, …), the
if statement will incorrectly result in
>>> x = numpy.array([0,]) >>> if x: print("x") ... else: print("No x") No x
x exists and is not empty! This result is not what you wanted.
len can give unexpected results
len( numpy.zeros((1,0)) )
returns 1, even though the array has zero elements.
The numpythonic way
As explained in the SciPy FAQ, the correct method in all cases where you know you have a NumPy array is to use
>>> x = numpy.array([0,1]) >>> if x.size: print("x") x >>> x = numpy.array([0,]) >>> if x.size: print("x") ... else: print("No x") x >>> x = numpy.zeros((1,0)) >>> if x.size: print("x") ... else: print("No x") No x
If you’re not sure whether it might be a
list, a NumPy array, or something else, you could combine this approach with this answer to make sure the right test is used for each type. Not very “pythonic”, but it turns out that NumPy intentionally broke pythonicity in at least this sense.
If you need to do more than just check if the input is empty, and you’re using other NumPy features like indexing or math operations, it’s probably more efficient (and certainly more common) to force the input to be a NumPy array. There are a few nice functions for doing this quickly — most importantly
dtype. So it’s very quick whenever it can be, and it ensures that you just get to assume the input is a NumPy array. We usually even just use the same name, as the conversion to an array won’t make it back outside of the current scope:
x = numpy.asarray(x, dtype=numpy.double)
This will make the
x.size check work in all cases I see on this page.
I had written:
if isinstance(a, (list, some, other, types, i, accept)) and not a: do_stuff
which was voted -1. I’m not sure if that’s because readers objected to the strategy or thought the answer wasn’t helpful as presented. I’ll pretend it was the latter, since—whatever counts as “pythonic”—this is the correct strategy. Unless you’ve already ruled out, or are prepared to handle cases where
a is, for example,
False, you need a test more restrictive than just
if not a:. You could use something like this:
if isinstance(a, numpy.ndarray) and not a.size: do_stuff elif isinstance(a, collections.Sized) and not a: do_stuff
the first test is in response to this answer above. The third line could also be replaced with:
elif isinstance(a, (list, tuple)) and not a:
if you only want to accept instances of particular types (and their subtypes), or with:
elif isinstance(a, (list, tuple)) and not len(a):
You can get away without the explicit type check, but only if the surrounding context already assures you that
a is a value of the types you’re prepared to handle, or if you’re sure that types you’re not prepared to handle are going to raise errors (e.g., a
TypeError if you call
len on a value for which it’s undefined) that you’re prepared to handle. In general, the “pythonic” conventions seem to go this last way. Squeeze it like a duck and let it raise a DuckError if it doesn’t know how to quack. You still have to think about what type assumptions you’re making, though, and whether the cases you’re not prepared to handle properly really are going to error out in the right places. The Numpy arrays are a good example where just blindly relying on
len or the boolean typecast may not do precisely what you’re expecting.
Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that’s a strong signal.
It’s true that
if not a: doesn’t distinguish empty lists from
None, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it’s important to be explicit about that. And in that case, you know what you want to be explicit about, so you can test for exactly that. For example,
if not a and a is not None: means “anything falsey except None”, while
if len(a) != 0: means “only empty sequences—and anything besides a sequence is an error here”, and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.
But when you don’t have anything to be explicit about, anything other than
if not a: is misleading the reader. You’re signaling something as important when it isn’t. (You may also be making the code less flexible, or slower, or whatever, but that’s all less important.) And if you habitually mislead the reader like this, then when you do need to make a distinction, it’s going to pass unnoticed because you’ve been “crying wolf” all over your code.
Why check for empty list at all?
No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to check this in the first place but are unfamiliar with list processing in Python.
I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
a =  for item in a: <do something with item> <rest of code>
This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient.
Hope you learned something from this post.
Follow Programming Articles for more!