Best way to check if a list is empty

0 votes
asked Sep 10, 2008 by ray-vega

For example, if passed the following:

a = []

How do I check to see if a is empty?

21 Answers

0 votes
answered by dubiousjim

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 @Mike's 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.

0 votes
answered Sep 10, 2008 by patrick
if not a:
  print("List is empty")

Using the implicit booleanness of the empty list is quite pythonic.

0 votes
answered Sep 10, 2008 by hazzen

I have seen the below as preferred, as it will catch the null list as well:

if not a:
    print "The list is empty or null"
0 votes
answered Sep 10, 2008 by peter-hoffmann

An empty list is itself considered false in true value testing (see python documentation):

a = []
if a:
     print "not empty"

@Daren Thomas

EDIT: Another point against testing the empty list as False: What about polymorphism? You shouldn't depend on a list being a list. It should just quack like a duck - how are you going to get your duckCollection to quack ''False'' when it has no elements?

Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.

0 votes
answered Sep 10, 2008 by verix

I prefer the following:

if a == []:
   print "The list is empty."

Readable and you don't have to worry about calling a function like len() to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unless a was gigantic.

0 votes
answered Sep 10, 2008 by harley-holcombe

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.

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):
0 votes
answered Sep 15, 2008 by george-v-reilly

len() is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.

JavaScript has a similar notion of truthy/falsy.

0 votes
answered Sep 5, 2011 by jabba

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 the false impression that li is a boolean variable.

0 votes
answered Sep 2, 2012 by octopusgrabbus

Python is very uniform about the treatment of emptiness. Given the following:

a = []

.
.
.

if a:
   print("List is not empty.")
else:
   print("List is empty.")

You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.

0 votes
answered Sep 21, 2012 by mike

Other methods don't work for numpy arrays

Other people seem to be generalizing your 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. You need to be careful with numpy arrays, because other methods that work fine for lists fail for numpy arrays. I explain why below, but in short, the preferred method is to use size.

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 bools, and 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 ValueError:

>>> 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 0 (or 0.0, or false, ...), the if statement will incorrectly result in false:

>>> x = numpy.array([0,])
>>> if x: print("x")
... else: print("No x")
No x

But clearly x exists and is not empty! This result is not what you wanted.

Using len can give unexpected results

For example,

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 if x.size:

>>> 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 should combine this approach with the answer @dubiousjim gives to make sure the right test is used for each type. Not very "pythonic", but it turns out that numpy isn't pythonic in at least this sense...

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...