By Ray

2008-09-10 06:20:11 8 Comments

For example, if passed the following:

a = []

How do I check to see if a is empty?


@Patrick 2008-09-10 06:28:05

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

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

@James McMahon 2011-11-22 06:14:02

Playing devil's advocate. I don't understand why this idiom is considered pythonic. 'Explicit is better then implicit', correct? This check doesn't seem very explicit about what is is checking.

@andrew cooke 2012-05-31 14:50:08

@JamesMcMahon - it's a trade-off between explicitness and type flexibility. generally, "being explicit" means not doing "magical" things. on the other hand, "duck typing" means working with more general interfaces, rather than explicitly checking for types. so something like if a == [] is forcing a particular type (() == [] is False). here, general consensus seems to be that duck typing wins out (in effect, saying that __nonzero__ is the interface for testing emptiness

@Mr.WorshipMe 2019-03-20 18:01:33

This method doesn't work on numpy arrays.. so I think if len(a) == 0 is preferable both in terms of "duck typing" and implicitness.

@sleblanc 2019-04-02 23:55:42

The canonical way of knowing if an array in C is empty is by dereferencing the first element and seeing if it is null, assuming an array that is nul-terminated. Otherwise, comparing its length to zero is utterly inefficient if the array is of a significant size. Also, typically, you would not allocate memory for an empty array (pointer remains null), so it makes no sense to attempt to get its length. I am not saying that len(a) == 0 is not a good way of doing it, it just does not scream 'C' to me when I see it.

@Brennen Sprimont 2019-04-14 04:52:39

@sleblanc I've never seen a null terminated array in c outside of implementing a string, the common case is not to null terminate. "comparing its length to zero is utterly inefficient" is incorrect, there is no c implementation in existence where this would cost more than a couple cycles. Comparing the length of an array to 0 to determine emptiness is standard practice in c and almost all c influenced languages (c++, java, c#, etc).

@sleblanc 2019-04-14 16:03:18

@BrennenSprimont, If it's not null-terminated, then you already know the length, whether it is stored in a separate variable or your array is wrapped in some container that tracks the length. C++, Java, C# have such containers and implement some "length" method efficiently. C has no such thing, you have to roll your own. Statically allocated C arrays are just pointers to a memory space that is guaranteed to have enough space to store the amount of data you have requested. There is nothing built into C that will let you know how much you have filled that space already.

@Inherited Geek 2019-08-25 01:39:17

Another similar way: print (bool(not a))

@Mr Matrix 2019-11-28 04:51:54

If you are using this on a custom object i.e. "if not customObject" then make sure you implement the len method in your custom object class definition else it will evaluate to False even on an empty object.

@Mihai.Mehe 2020-03-10 18:28:32

A simple variation in one line: 'Empty' if not a else 'Full' like so: 'Empty' if not [1] else 'Full'

@Théo Simier 2020-03-18 11:25:22

When using Numpy and according to its documentation, you should use:array.size > 0 Else you would have the following message. DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use array.size > 0 to check that an array is not empty.

@Edwin Rodríguez 2020-04-04 14:03:17

Coming from a language that claims to be some sort of poetry, this mechanism is pure garbage. Semantically, being empty is very different to not being

@ThunderPheonix 2020-04-13 10:28:15

We can use if(len(a) == 0): too

@user2357112 supports Monica 2020-05-21 23:01:06

@Mr.WorshipMe: if len(a) == 0 doesn't work for NumPy arrays either, because it fails for shapes like (5, 0). A 5-by-0 array is empty, but has length 5. The check for a NumPy array would be a.size == 0 (or not a.size), which doesn't work for a list.

@dzieciou 2020-05-30 11:08:53

It will print that a is empty for a = None considered empty, because not bool(None) == True.

@Andy 2018-12-26 00:05:06

To check whether a list is empty or not you can use two following ways. But remember, we should avoid the way of explicitly checking for a type of sequence (it's a less pythonic way):

def enquiry(list1): 
    if len(list1) == 0: 
        return 0
        return 1

# ––––––––––––––––––––––––––––––––

list1 = [] 

if enquiry(list1): 
    print ("The list isn't empty") 
    print("The list is Empty") 

# Result: "The list is Empty".

The second way is a more pythonic one. This method is an implicit way of checking and much more preferable than the previous one.

def enquiry(list1): 
    if not list1: 
        return True
        return False

# ––––––––––––––––––––––––––––––––

list1 = [] 

if enquiry(list1): 
    print ("The list is Empty") 
    print ("The list isn't empty") 

# Result: "The list is Empty"

Hope this helps.

@Rahul 2018-03-05 11:30:01

If you want to check if a list is empty:

l = []
if l:
    # do your stuff.

If you want to check whether all the values in list is empty. However it will be True for an empty list:

l = ["", False, 0, '', [], {}, ()]
if all(bool(x) for x in l):
    # do your stuff.

If you want to use both cases together:

def empty_list(lst):
    if len(lst) == 0:
        return False
        return all(bool(x) for x in l)

Now you can use:

if empty_list(lst):
    # do your stuff.

@gberger 2018-03-05 17:27:17

all(bool(x) for x in l) is True for an empty list

@Tagar 2016-04-13 21:55:32

def list_test (L):
    if   L is None  : print('list is None')
    elif not L      : print('list is empty')
    else: print('list has %d elements' % len(L))


It is sometimes good to test for None and for emptiness separately as those are two different states. The code above produces the following output:

list is None 
list is empty 
list has 3 elements

Although it's worth nothing that None is falsy. So if you don't want to separate test for None-ness, you don't have to do that.

def list_test2 (L):
    if not L      : print('list is empty')
    else: print('list has %d elements' % len(L))


produces expected

list is empty
list is empty
list has 3 elements

@Aaron Hall 2017-08-20 03:50:58

Best way to check if a list is empty

For example, if passed the following:

a = []

How do I check to see if a is empty?

Short Answer:

Place the list in a boolean context (for example, with an if or while statement). It will test False if it is empty, and True otherwise. For example:

if not a:                           # do this!
    print('a is an empty list')


PEP 8, the official Python style guide for Python code in Python's standard library, asserts:

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

We should expect that standard library code should be as performant and correct as possible. But why is that the case, and why do we need this guidance?


I frequently see code like this from experienced programmers new to Python:

if len(a) == 0:                     # Don't do this!
    print('a is an empty list')

And users of lazy languages may be tempted to do this:

if a == []:                         # Don't do this!
    print('a is an empty list')

These are correct in their respective other languages. And this is even semantically correct in Python.

But we consider it un-Pythonic because Python supports these semantics directly in the list object's interface via boolean coercion.

From the docs (and note specifically the inclusion of the empty list, []):

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)

And the datamodel documentation:


Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.



Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

So instead of this:

if len(a) == 0:                     # Don't do this!
    print('a is an empty list')

or this:

if a == []:                     # Don't do this!
    print('a is an empty list')

Do this:

if not a:
    print('a is an empty list')

Doing what's Pythonic usually pays off in performance:

Does it pay off? (Note that less time to perform an equivalent operation is better:)

>>> import timeit
>>> min(timeit.repeat(lambda: len([]) == 0, repeat=100))
>>> min(timeit.repeat(lambda: [] == [], repeat=100))
>>> min(timeit.repeat(lambda: not [], repeat=100))

For scale, here's the cost of calling the function and constructing and returning an empty list, which you might subtract from the costs of the emptiness checks used above:

>>> min(timeit.repeat(lambda: [], repeat=100))

We see that either checking for length with the builtin function len compared to 0 or checking against an empty list is much less performant than using the builtin syntax of the language as documented.


For the len(a) == 0 check:

First Python has to check the globals to see if len is shadowed.

Then it must call the function, load 0, and do the equality comparison in Python (instead of with C):

>>> import dis
>>> dis.dis(lambda: len([]) == 0)
  1           0 LOAD_GLOBAL              0 (len)
              2 BUILD_LIST               0
              4 CALL_FUNCTION            1
              6 LOAD_CONST               1 (0)
              8 COMPARE_OP               2 (==)
             10 RETURN_VALUE

And for the [] == [] it has to build an unnecessary list and then, again, do the comparison operation in Python's virtual machine (as opposed to C)

>>> dis.dis(lambda: [] == [])
  1           0 BUILD_LIST               0
              2 BUILD_LIST               0
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE

The "Pythonic" way is a much simpler and faster check since the length of the list is cached in the object instance header:

>>> dis.dis(lambda: not [])
  1           0 BUILD_LIST               0
              2 UNARY_NOT
              4 RETURN_VALUE

Evidence from the C source and documentation


This is an extension of PyObject that adds the ob_size field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the PyObject_VAR_HEAD macro.

From the c source in Include/listobject.h:

typedef struct {
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size

Response to comments:

I would point out that this is also true for the non-empty case though its pretty ugly as with l=[] then %timeit len(l) != 0 90.6 ns ± 8.3 ns, %timeit l != [] 55.6 ns ± 3.09, %timeit not not l 38.5 ns ± 0.372. But there is no way anyone is going to enjoy not not l despite triple the speed. It looks ridiculous. But the speed wins out
I suppose the problem is testing with timeit since just if l: is sufficient but surprisingly %timeit bool(l) yields 101 ns ± 2.64 ns. Interesting there is no way to coerce to bool without this penalty. %timeit l is useless since no conversion would occur.

IPython magic, %timeit, is not entirely useless here:

In [1]: l = []                                                                  

In [2]: %timeit l                                                               
20 ns ± 0.155 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

In [3]: %timeit not l                                                           
24.4 ns ± 1.58 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [4]: %timeit not not l                                                       
30.1 ns ± 2.16 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

We can see there's a bit of linear cost for each additional not here. We want to see the costs, ceteris paribus, that is, all else equal - where all else is minimized as far as possible:

In [5]: %timeit if l: pass                                                      
22.6 ns ± 0.963 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [6]: %timeit if not l: pass                                                  
24.4 ns ± 0.796 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [7]: %timeit if not not l: pass                                              
23.4 ns ± 0.793 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Now let's look at the case for an unempty list:

In [8]: l = [1]                                                                 

In [9]: %timeit if l: pass                                                      
23.7 ns ± 1.06 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [10]: %timeit if not l: pass                                                 
23.6 ns ± 1.64 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [11]: %timeit if not not l: pass                                             
26.3 ns ± 1 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

What we can see here is that it makes little difference whether you pass in an actual bool to the condition check or the list itself, and if anything, giving the list, as is, is faster.

Python is written in C; it uses its logic at the C level. Anything you write in Python will be slower. And it will likely be orders of magnitude slower unless you're using the mechanisms built into Python directly.

@Gregory Morse 2019-11-28 05:52:15

I would point out that this is also true for the non-empty case though its pretty ugly as with l=[] then %timeit len(l) != 0 90.6 ns ± 8.3 ns, %timeit l != [] 55.6 ns ± 3.09, %timeit not not l 38.5 ns ± 0.372. But there is no way anyone is going to enjoy not not l despite triple the speed. It looks ridiculous. But the speed wins out

@Gregory Morse 2019-11-28 06:31:53

I suppose the problem is testing with timeit since just if l: is sufficient but surprisingly %timeit bool(l) yields 101 ns ± 2.64 ns. Interesting there is no way to coerce to bool without this penalty. %timeit l is useless since no conversion would occur.

@Andrey Suglobov 2018-11-03 02:23:02

print('not empty' if a else 'empty')

a little more practical:

a.pop() if a else None

and shertest version:

if a: a.pop() 

@l. zhang 2019-01-06 19:15:13

we could use a simple if else:

if len(item_list) == 0:
    print("list is empty")
    print("list is not empty")

@MrWonderful 2019-04-29 09:08:52

-1 - To avoid confusion, don't use a reserved words for variable names or you may get surprising behavior next time you try to call, for instance "list()"... something like "TypeError: 'list' object is not callable" or some such.

@Vedran Šego 2019-04-24 15:07:03

What brought me here is a special use-case: I actually wanted a function to tell me if a list is empty or not. I wanted to avoid writing my own function or using a lambda-expression here (because it seemed like it should be simple enough):

foo = itertools.takewhile(is_not_empty, (f(x) for x in itertools.count(1)))

And, of course, there is a very natural way to do it:

foo = itertools.takewhile(bool, (f(x) for x in itertools.count(1)))

Of course, do not use bool in if (i.e., if bool(L):) because it's implied. But, for the cases when "is not empty" is explicitly needed as a function, bool is the best choice.

@Mike 2012-02-21 16:48:02

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 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 = numpy.array([0,])
>>> if x.size: print("x")
... else: print("No 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 the answer @dubiousjim gives 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 numpy.asarray. This takes your input, does nothing if it's already an array, or wraps your input into an array if it's a list, tuple, etc., and optionally converts it to your chosen 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.

@Gareth Latty 2015-02-16 20:47:12

It's worth noting that this isn't a flaw in Python, but rather an intentional break of contract by numpy - numpy is a library with a very specific use case, and it has a different 'natural' definition of what truthiness on an array is to the Python standard for containers. It makes sense to optimise for that case, in the way that pathlib uses / to concatenate paths instead of + - it's non-standard, but makes sense in context.

@Mike 2015-02-16 21:21:02

Agreed. My point is just that it's important to remember that numpy has made the choice to break duck typing for both the very common if x and len(x) idioms -- and sometimes that breakage can be very hard to detect and debug.

@Dalton 2015-08-20 19:54:14

I don't know, for me, if a method called len(x) doesn't return the array length because assumptions, it's name is bad designed.

@pydsigner 2016-03-10 17:33:42

@Dalton I disagree on this interpretation of len() on numpy arrays. If you convert numpy.zeros((1,0)) to a list, you get [[]], which is boolean true. The numpy array isn't empty because it contains one (empty) array.

@Mike 2016-03-10 21:36:16

@pydsigner I agree with your conclusion, but I'll quibble with your logic -- particularly your last sentence. numpy.zeros((1,0)) is definitely not an array containing one (empty) array; it is just a single array containing no elements. Numpy arrays are not nested. When you run tolist you do get a list containing one (empty) list -- but that's a different beast entirely. On the other hand, it appears that len just gives the size of the first dimension of an array. This isn't wrong; it's just a choice (though one I would not have made).

@pydsigner 2016-03-10 22:47:32

@Mike While the str() of a 1x0 array is [], running for sub in numpy.zeros((1,0)): print sub will output [] as the inner array rather than printing nothing. A quirk of array representation should not determine how we view the construct.

@Mike 2016-03-11 00:23:22

I'm not sure I get your point. If you print(type(sub)) in your example you get <class 'numpy.ndarray'> -- not list. Anyway, that's beside the point because it just means they've implemented iteration. There's no quirk about this: from their python-level interface, to the C API implementation, right down to their layout in memory, numpy arrays are multi-dimensional arrays, not nested arrays or lists. You can slice them to extract sub-arrays, but that's got nothing to do with nesting.

@pppery 2017-07-31 18:58:37

This question has nothing to do with numpy arrays

@peterhil 2017-09-12 21:22:04

@ppperry Yes, the original question was not about Numpy arrays, but when working with those and possibly duck typed arguments, this question becomes very relevant.

@Bas Swinckels 2017-11-09 11:31:38

The nympythonic way in case you also want to make your code work if a list is given is to first force any possible input to a numpy array using asarray. After that, you can proceed as in your answer without worrying about other formats.

@Mike 2017-11-09 14:40:33

@BasSwinckels Good point. I'm guessing it's not always worth the effort if the only thing you want to do is check if the input is empty, but certainly that's what we usually do when we want to actually do things with the input. I'll add that to my answer. Thanks.

@plugwash 2018-09-26 21:47:00

"len( numpy.zeros((1,0)) ) returns 1, even though the array has zero elements." It's IMO not terribly different from a list containing an empty list. both have a len of 1 and result in a single iteration when you loop over them.

@Mike 2018-09-27 18:16:02

@plugwash This was brought up above, so I'll just reiterate that everything else about numpy — from its C code to other aspects of its high-level interface — says that an array is definitely not a nested type of object; it is a single multi-dimensional object. That is, numpy.zeros((1,0)) is not supposed to be considered an array containing another array (that just happens to be empty). Instead, it's supposed to be considered a single two-dimensional array containing no elements. And as a result, you need to remain aware of the distinction whenever you test for an empty array.

@Marco Sulla 2020-02-15 19:01:50

@GarethLatty: not at all. The / can be applied only between a Path and a str or a path-like object. And this is very pythonic, since Python is a strong typed language. Furthermore, + seems more a concatenation between strings, and this is not the behavior of joining paths (try, for example, Path("a") / "b/"). Lastly, is much more elegant to join paths with /. On the contrary, numpy implemented operators between cats and dogs. This way, they completely broken any Python contract.

@Marco Sulla 2020-02-15 19:04:12

@GarethLatty: for example, ff I want to create a function that can accept any iterable, and I have to use bool() or len(), I'm forced to check if the iterable is an ndarray and threat it in a different way. So where is gone Duck Typing? The duck was eaten by numpy, hungry to attract Matlab users :-D

@Vikrant 2019-02-09 23:59:54

Method 1 (Preferred):

if not a : 
   print ("Empty") 

Method 2 :

if len(a) == 0 :
   print( "Empty" )

Method 3:

if a == [] :
  print ("Empty")

@verix 2008-09-10 06:43:14

I prefer the following:

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

@Carl Meyer 2008-09-10 13:42:00

This is going to be slower, as you instantiate an extra empty list unnecessarily.

@devsnd 2012-11-12 11:23:26

this is less readable than if not a: and breaks more easily. Please don't do it.

@A Star 2019-03-16 21:03:31

There is a good point made earlier () == [] is also equal to false. Although I like how this implementation reads the if not a: covers all cases, if you are definitely expecting a list then your example should be sufficient.

@Tessaracter 2018-11-06 09:55:45

From python3 onwards you can use

a == []

to check if the list is empty

EDIT : This works with python2.7 too..

I am not sure why there are so many complicated answers. It's pretty clear and straightforward

@ganeshdeshmukh 2018-12-30 10:48:00

please give more explanation about how it is working without writing "if"?

@MrWonderful 2019-04-29 08:53:32

This is not pythonic nor a complete example. Also, It instantiates an empty list every time it is encountered. Don't do this.

@Tessaracter 2020-04-06 15:44:54

@MrWonderful it does not instantiate an empty list every time. It just verifies if the existing list a is empty or not.

@Tessaracter 2020-04-06 15:45:29

@MrWonderful I don't get what makes it pythonic

@Tessaracter 2020-04-06 15:47:07

@ganeshdeshmukh if you use a==[] it will print true on the python terminal if a is empty. Else it will print False. You can use this inside a if condition also as if(a==[])

@HackerBoss 2018-10-12 04:01:59

Many answers have been given, and a lot of them are pretty good. I just wanted to add that the check

not a

will also pass for None and other types of empty structures. If you truly want to check for an empty list, you can do this:

if isinstance(a, list) and len(a)==0:
    print("Received an empty list")

@Sven Krüger 2019-01-10 09:40:10

It is possible this throws an exception, if a is not a list and a has no method __len__ implemented. I would recommend: if isinstance(obj, list): if len(obj) == 0: print '...'

@ElmoVanKielmo 2019-02-26 14:00:29

@SvenKrüger nope. Operator and is lazy in Python. Nothing after and is going to be executed if condition before and is False.

@Ashiq Imran 2018-10-12 02:59:58

Simple way is checking the length is equal zero.

if len(a) == 0:
    print("a is empty")

@MiloMinderbinder 2018-05-16 04:13:04

The truth value of an empty list is False whereas for a non-empty list it is True.

@Harley Holcombe 2008-09-10 10:33:38

The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):

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

@BallpointBen 2018-05-10 18:44:42

The second way seems better if you wish to signal that seq is expected to be some sort of list-like object.

@axolotl 2018-07-14 05:35:39

@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible

@Boris 2019-01-04 23:46:56

@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.

@Mr.WorshipMe 2019-03-20 18:03:33

numpy broke this idiom... seq = numpy.array([1,2,3]) followed by if not seq raises an exception "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

@aafulei 2019-09-26 02:34:34

Despite all Pythonic advocates, I am with @BallpointBen in that if you mistakenly wrote seq = [0] as seq = 0, len(seq) will help you catch the error. To err is human. So is a programmer.

@jeronimo 2019-10-22 11:24:16

I just got this message in using Python 3.6.4: "FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead." so I guess this clearly defines the preference

@Harley Holcombe 2019-10-23 16:05:39

@jeronimo: I believe that is an lxml-specific warning.

@MrWonderful 2015-10-06 19:25:34

Why check 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 do this check 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.

@Amarth Gûl 2018-02-02 14:02:48

The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside <rest of code> that might use the result from the for loop? Or directly use some values in a? Indeed, if the script is designed to run with strictly controlled input, the check might be a little unnecessary. But in most cases, the input varies, and have a check is usually better.

@MrWonderful 2018-02-17 19:18:43

Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.

@MrWonderful 2018-05-22 22:45:27

@AmarthGûl - How might one get the results from the for loop to the script inside <rest of code> to be processed? In a list, perhaps? Or maybe a dict? If so, the same logic applies. I'm not understanding how variable input could have any effect within any kind of reasonably designed code, where processing an empty list would be a bad idea.

@DJK 2019-06-24 22:30:32

A bit old but if you were just checking if the list was empty, for a non empty list your code repeats the process over and over when OP is simply looking for a check operation. Just imagine a worse case scenario for that code as n approaches infinity....

@MrWonderful 2019-06-26 00:14:38

@DJK I believe you may have missed the point, but for an empty list, the code falls through. For a non-empty list, you just process each element as you need to. The point was “in most cases, no check for empty is necessary.” This is doubly so because the OP didn’t know that “if a_list:” was the correct answer, therefore was potentially a novice python developer.

@DJK 2019-06-26 02:21:00

No you’ve created an O(n) problem on a check. your only considering a good outcome on an empty list. The answer works but in my opinion it’s sub optimal

@MrWonderful 2019-06-27 04:07:53

@DJK - Nope, I think you’re still missing it. Presumably you want to DO something with a list, if you have one. What would you do differently if it were empty? Return early? What if it isn’t empty? process it? The point is, still, that you probably don’t need to check for an empty list, just iterate over it and do whatever you were going to do with the elements. If there are no elements, you fall through. If there are elements, you process them as you need to. The point is NOT to use the example FOR an empty-check but rather to NOT check at all, just process the list.

@Vineet Jain 2017-08-26 19:04:05

Simply use is_empty() or make function like:-

def is_empty(any_structure):
    if any_structure:
        print('Structure is not empty.')
        return True
        print('Structure is empty.')
        return False  

It can be used for any data_structure like a list,tuples, dictionary and many more. By these, you can call it many times using just is_empty(any_structure).

@Davis Herring 2017-09-20 02:39:05

The name is_empty suggests that it returns something. But if it did, that something would just be bool(any_structure), which you should use instead (when you need a bool at all).

@Davis Herring 2017-09-20 03:13:03

Why do we want a variation on bool that (also) prints messages to standard output?

@Vineet Jain 2017-09-20 03:45:30

@DavisHerring We always have two choice first is to print using function other is using return bool variable. Choice is yours. I write both so you can choose between them.

@Jabba 2011-09-05 00:30:30

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.

@Carl Smith 2013-07-09 13:43:53

Checking if the length of a list is equal to zero, rather than just checking if the list is false, is ugly and unpythonic. Anyone familiar with Python will not think li is a bool at all, and wont care. If it's important, you should add a comment, not more code.

@John B 2014-06-23 14:46:46

This seems like an unnecessarily precise test, which is often slower and is always less readable IMHO. Instead of checking the size of something empty, why not just check if it's empty?

@abarnert 2014-12-03 02:05:52

Anyway, the reason this is bad (and that violating idioms in a language with strong idioms like Python is bad in general) is that it signals to the reader that you're specifically checking the length for some reason (e.g., because you want None or 0 to raise an exception rather than passing). So, when you do it for no reason, that's misleading—and it also means that when your code does need to make the distinction, the distinction is invisible because you've "cried wolf" all over the rest of the source.

@augurar 2015-01-05 19:40:05

I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" with if bool(len(li) == 0) is True:?

@ralokt 2015-11-19 13:04:15

@Jabba it will be O(1) in many cases (those where you work with the built-in data types), but you just can't rely on that. You might be working with a custom data type that doesn't have this property. You might also decide to add this custom data type later, after you already wrote this code.

@yo' 2017-01-07 20:42:57

It is very bad to grab the length only to check for emptiness. This is not good in any way.

@jamylak 2018-02-17 10:33:32

This is anti PEP 8

@BallpointBen 2018-05-10 18:44:07

What if you do want to raise an exception for types without a __len__? This is perfect in that case.

@Johan 2018-06-15 05:51:55

If it is unclear li is a list, maybe you shouldn't have named it li. I think there are very few good variable names with only 2 letters. What about cars or evasive_manoeuvres? Booleans on the other hand should have an is or has or other verb in the name, compare if is_evasive_manoeuvre: and if evasive_maoeuvres. It is clear to me which is a bool and which is a collection.

@Armstrongest 2019-06-07 16:26:15

It's like showing your friend a container full of 0 oranges. It's not a container of oranges... and if it doesn't contain anything... then it could be argued to be a container at all. It only becomes a container containing contents once contents are contained. (x_x)

@dzieciou 2020-05-30 11:24:20

At least it won't say that a is empty for a == None, while not a would evaluate to True for a == None.

@AndreyS Scherbakov 2017-03-29 02:58:02

Being inspired by @dubiousjim's solution, I propose to use an additional general check of whether is it something iterable

import collections
def is_empty(a):
    return not a and isinstance(a, collections.Iterable)

Note: a string is considered to be iterable. - add and not isinstance(a,(str,unicode)) if you want the empty string to be excluded


>>> is_empty('sss')
>>> is_empty(555)
>>> is_empty(0)
>>> is_empty('')
>>> is_empty([3])
>>> is_empty([])
>>> is_empty({})
>>> is_empty(())

@pppery 2017-07-12 15:47:09

Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.

@Davis Herring 2017-09-20 02:40:33

If I wasn't happy with if a:, it would be because I wanted an exception if a wasn't some sort of container. (Being an iterable also allows iterators, which can't usefully be tested for emptiness.)

@Inconnu 2016-11-28 14:18:03

Here are a few ways you can check if a list is empty:

a = [] #the list

1) The pretty simple pythonic way:

if not a:
    print("a is empty")

In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False. One could simply treat the list as a predicate (returning a Boolean value). And a True value would indicate that it's non-empty.

2) A much explicit way: using the len() to find the length and check if it equals to 0:

if len(a) == 0:
    print("a is empty")

3) Or comparing it to an anonymous empty list:

if a == []:
    print("a is empty")

4) Another yet silly way to do is using exception and iter():

    # list has elements
except StopIteration:
    print("Error: a is empty")

@Sunil Lulla 2016-09-13 11:53:56

You can even try using bool() like this

    a = [1,2,3];
    print bool(a); # it will return True
    a = [];
    print bool(a); # it will return False

I love this way for checking list is empty or not.

Very handy and useful.

@Galen Long 2017-03-10 21:42:15

For those (like me) who didn't know, bool() converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.

@qneill 2017-12-18 21:13:24

This is usable in an expression and is more terse.

@Sнаđошƒаӽ 2016-01-01 18:18:58

From documentation on truth value testing:

All values other than what is listed here are considered True

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

As can be seen, empty list [] is falsy, so doing what would be done to a boolean value sounds most efficient:

if not a:
    print('"a" is empty!')

@Sнаđошƒаӽ 2018-09-01 05:39:51

@DJ_Stuffy_K assert what in unit testing, an empty list? Just use assert(not myList). If you also want to assert the object is a list, you can use assertIsInstance().

@dubiousjim 2012-05-31 14:35:05

I had written:

if isinstance(a, (list, some, other, types, i, accept)) and not a:

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:
elif isinstance(a, collections.Sized) and not a:

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.

@abarnert 2014-12-03 02:09:53

It's pretty rare that you're going to have an exhaustive list of 6 types that you want to accept and not be flexible for any other types. When you need that kind of thing, you probably want an ABC. In this case, it would probably be one of the stdlib ABCs, like or, but it might be one you write yourself and register(list) on. If you actually do have code where it's important to distinguish empty from other falsey, and also to distinguish lists and tuples from any other sequences, then this is correct—but I don't believe you have such code.

@Gareth Latty 2015-02-16 20:54:10

The reason people don't like this is because it's entirely unnessesary in most cases. Python is a duck-typed language, and this level of defensive coding actively hinders that. The idea behind Python's type system is that things should work as long as the object passed in functions in the way it needs to. By doing explicit type checks you are forcing the caller to use specific types, going against the very grain of the language. While occasionally such things are necessary (excluding strings from being treated as sequences), such cases are rare and almost always best as blacklists.

@RemcoGerlich 2015-07-16 13:10:54

If you really want to check that the value is exactly [] and not something falsy of another type, then surely if a == []: is called for, rather than mucking about with isinstance.

@dubiousjim 2015-07-16 13:36:41

There are some automatic coercions for == though. Off the top of my head, I can't identify any for []. [] == () for instance returns False. But for example frozenset()==set() returns True. So it's worth at least giving some thought to whether some undesired type might be coerced to [] (or vice versa) when doing a == [].

@MrWonderful 2018-10-12 04:47:51

@RemcoGerlich - isinstance() is still preferable as opposed to constructing an empty list to compare against. Also, as another pointed out, the equality operator may invoke implicit conversion of some types, which may be undesirable. There is no reason to ever code "a == []" and that code would definitely be flagged as a defect in any code review I've participated in. Using the appropriate tool as provided by the language should not be considered "mucking about," but rather "good programming technique."

@Boris 2019-05-11 07:07:49

Instead of manually checking types you should use type hinting (introduced in 3.5).

@Tim 2019-07-10 02:10:17

@Boris Type hints help static type checkers (like mypy) to check for type correctness but do not perform runtime type checking.

@abarnert 2014-12-03 02:21:29

Patrick's (accepted) answer is right: if not a: is the right way to do it. Harley Holcombe's answer is right that this is in the PEP 8 style guide. But what none of the answers explain is why it's a good idea to follow the idiom—even if you personally find it's not explicit enough or confusing to Ruby users or whatever.

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.

@Peter Hoffmann 2008-09-10 06:31:22

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.

@information_interchange 2019-10-14 03:34:00

Strange how [] == False will evaluate to False though

@augurar 2019-10-20 07:29:08

@information_interchange If you want to explicitly check the truthiness of a value, use bool(). bool([]) == False will evaluate to True as expected.

@George V. Reilly 2008-09-15 05:50:48

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.

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

39 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

20 Answered Questions

[SOLVED] Accessing the index in 'for' loops?

  • 2009-02-06 22:47:54
  • Joan Venge
  • 2111626 View
  • 3598 Score
  • 20 Answer
  • Tags:   python loops list

7 Answered Questions

[SOLVED] How do I get the number of elements in a list?

  • 2009-11-11 00:30:54
  • y2k
  • 3259276 View
  • 1934 Score
  • 7 Answer
  • Tags:   python list

18 Answered Questions

[SOLVED] How to clone or copy a list?

40 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

26 Answered Questions

[SOLVED] How do I pass a variable by reference?

30 Answered Questions

[SOLVED] Finding the index of an item in a list

  • 2008-10-07 01:39:38
  • Eugene M
  • 3869599 View
  • 3165 Score
  • 30 Answer
  • Tags:   python list indexing

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 4319967 View
  • 3473 Score
  • 21 Answer
  • Tags:   python directory

24 Answered Questions

[SOLVED] How to check if the string is empty?

Sponsored Content