3228

For example, if passed the following:

a = []

How do I check to see if a is empty?

ayhan
  • 70,170
  • 20
  • 182
  • 203
Ray
  • 187,153
  • 97
  • 222
  • 204

27 Answers27

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

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Patrick
  • 90,362
  • 11
  • 51
  • 61
  • 1521
    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. – James McMahon Nov 22 '11 at 06:14
  • 280
    @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 http://docs.python.org/reference/datamodel.html#object.__nonzero__) – andrew cooke May 31 '12 at 14:50
  • 121
    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. – Mr.WorshipMe Mar 20 '19 at 18:01
  • 23
    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. – sleblanc Apr 02 '19 at 23:55
  • 12
    @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). – Brennen Sprimont Apr 14 '19 at 04:52
  • 7
    @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. – sleblanc Apr 14 '19 at 16:03
  • Another similar way: ``print (bool(not a)) `` – Inherited Geek Aug 25 '19 at 01:39
  • If you are using this on a custom object i.e. "if not customObject" then make sure you implement the [len](https://docs.python.org/3/reference/datamodel.html#object.__len__) method in your custom object class definition else it will evaluate to False even on an empty object. – Mr Matrix Nov 28 '19 at 04:51
  • 2
    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.` – Theo Mar 18 '20 at 11:25
  • 100
    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 – Edwin Rodríguez Apr 04 '20 at 14:03
  • We can use `if(len(a) == 0):` too – ThunderPhoenix Apr 13 '20 at 10:28
  • 2
    @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. – user2357112 May 21 '20 at 23:01
  • 2
    It will print that `a` is empty for `a = None` considered empty, because `not bool(None) == True`. – dzieciou May 30 '20 at 11:08
  • 3
    That is implicit, and therefore unpythonic, as "explicit is better than implicit". – yuvalm2 Aug 22 '20 at 09:00
  • `if bool([]) #False` `if bool([1,2,3]) #True` Just using `bool(list_name)` is the easiest way I feel. – Ash Singh Sep 03 '20 at 08:42
  • 1
    @ThunderPhoenix - One could also just use 'if len(a):' since a value >zero will evaluate to True... ;-) – MrWonderful Oct 15 '20 at 10:22
  • It's great that someone brought up that this is not applicable for a numpy array, but let's focus on the question `How do I check if a list is empty?`. We just want to check if the list is empty or not. I think this answer is good & pretty much pythonic and I completely agree with sleblanc. – Ice Bear Dec 19 '20 at 14:44
  • Thinking of it python has already had our backs it gives us already the truth value of sequences like , strings, lists,tuples as stated answer below. So we can just use it `DIRECTLY` and don't have to get the `len()` of it to check if it's `EMPTY` – Ice Bear Dec 19 '20 at 14:50
  • @andrewcooke I conclude that here duck type is used because it is general and does not check for a type. – Timo Jan 29 '21 at 20:49
  • 4
    I find it interesting that the question asks about checking if an empty list was passed and many are adamant that the solution needs to not differentiate between an empty list being passed and None being passed. Or 0 being passed. Without knowing what other possible values could be passed and whether they each represent a different case that needs to be handled, we can't assume that a broader test is appropriate. – David Moreau Mar 05 '21 at 18:29
  • 2
    Mr.WorshipMe is right. This method is not totally correct. [0] is not empty, but np.array([0]) is empty. [1] is not empty, np.array([1]) is not empty. weird. – Albert Chen Mar 25 '21 at 23:18
  • 1
    This example with a list ````myList = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9] for element in myList: if element not in newList: newList.append(element) print("The list with unique elements only:") print(myList) print(newList) ```` –  May 03 '21 at 18:43
  • In case you want a boolean variable, you can use something like: `is_list_element_present: bool = bool(my_list) # Empty lists are "falsy"` – DaHoC Jun 12 '21 at 12:26
  • @sleblanc, `len` is not `strlen`. `len` is a constant-time operation in Python. It stores the length of a sequence; it does not have to compute the length. https://wiki.python.org/moin/TimeComplexity – George V. Reilly Nov 01 '21 at 23:18
  • @EdwinRodríguez in Python there's a distinct difference between not existing and empty, but most of the time your code doesn't care. If it does you can use `if a is None`. – Mark Ransom Feb 09 '22 at 18:13
  • @sleblanc he's right. In Python everything is an object, and the standard sequence objects (list, tuple, string, etc.) keep track of their length so they don't need to count like C's `strlen` does. – Mark Ransom Feb 09 '22 at 18:18
  • @MarkRansom, you're out of your element. A now-deleted comment argued that the C way would look like "if len(l) == 0", to which I replied that it's utterly inefficient, because in C, if your list is a million elements long, checking if its length is 0 still means walking all its elements until a null item, then comparing it to zero. If you took a minute to read the rest of the conversation, you would have quickly understood that I'm more than acquainted with C. Try to keep up. – sleblanc Feb 10 '22 at 23:39
  • @sleblanc no need to be insulting. The question is about Python, and a Python list is exactly what I said it was and has no similarity to a linked list in C; it's more like a dynamically allocated array with an extra variable to track the length. You're right that getting the length of a linked list in C would be wildly inefficient, especially when all you need to do to see if the list is empty is look to see if the head pointer is null. Perhaps it's best that the other comment was deleted. – Mark Ransom Feb 11 '22 at 00:39
  • @sleblanc you're the one making assumptions - you assume I saw the parts of a conversation that were deleted. Given the context of the comments right now, I don't think what I said was out of line. I stand by the truth of it. – Mark Ransom Feb 12 '22 at 02:53
  • This is a bad design (the language and the example) because it conflates an empty structure with a non-existent structure. The two are not the same. As a silly analogy, a person holding an empty plate has no food, but has an empty plate. A person holding nothing has no food, but does not have an empty plate. – michael_teter Apr 06 '22 at 10:18
  • It's done by concept of `truthy-falsy' values – Azhar Uddin Sheikh Apr 07 '22 at 00:20
  • The tricky thing here is that it suggests you are dealing with a boolean here. It suggests that the inverse test `if a: print("non-empty")` is also dealing with a boolean. So far, it works. But be careful when using boolean operators: `False and [3,4]` gives False whereas `True and [3,4]` gives [3,4] – jeroent May 10 '23 at 12:40
1485

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):
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harley Holcombe
  • 175,848
  • 15
  • 70
  • 63
  • 123
    The second way seems better if you wish to signal that `seq` is expected to be some sort of list-like object. – BallpointBen May 10 '18 at 18:44
  • 21
    @BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible – axolotl Jul 14 '18 at 05:35
  • 14
    @BallpointBen try using Python's [type hinting](https://docs.python.org/3/library/typing.html) for signaling what a variable should be. It was introduced in 3.5. – Boris Verkhovskiy Jan 04 '19 at 23:46
  • 20
    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()" – Mr.WorshipMe Mar 20 '19 at 18:03
  • 17
    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. – aafulei Sep 26 '19 at 02:34
  • 1
    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 – jeronimo Oct 22 '19 at 11:24
  • 2
    @jeronimo: I believe that is an lxml-specific warning. – Harley Holcombe Oct 23 '19 at 16:05
  • 1
    @aafulei Polluting the source code with signals to help the programmer avoid coding errors is a fool's errand. Inelegantly imposing this misplaced concern on the source code results in code that is harder to read and follow, which over the life of the code leads to the introduction of more bugs, not fewer. Tests exist to address the concern of (continuously) ensuring correctness and to keep that concern separated from any others. I am a Python newbie btw, there is nothing Pythonic about these statements, they reflect basic SRP principles that can and should be expressed in any given language. – mouselabs Jun 28 '20 at 04:46
  • 1
    @Mr.WorshipMe I agree that numpy breaks the paradigm, so boolean-ness is a bad habit to use, since it doesn't extend to all iterables. BUT others shouldn't think that the error-message you cite gives the general solution for sequences, since `any( [0,False,"",[]] )` returns `False` even though there are four items in the list. – not-just-yeti Apr 18 '22 at 17:35
  • 1
    I'm getting `The truth value of an array with more than one element is ambiguous` while using `if seq` – Vulwsztyn Sep 23 '22 at 17:07
  • 1
    @Mr.WorshipMe: `numpy` breaks all kinds of rules that built-in Python types obey. Python's general rule is that collections are falsy if empty, true otherwise, numeric types are falsy if `0`, true otherwise, `None` is falsy, and everything else is true. Saying "The idiom is bad because third-party libraries broke the rules" is going to break *every* idiom. If your code isn't intended to work with `numpy` arrays, just built-in collections, this is the correct way to do it. The only completely correct `numpy` solutions (`if not array.size:`) won't work on any built-in anyway. – ShadowRanger Nov 14 '22 at 21:02
1088

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.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Jabba
  • 19,598
  • 6
  • 52
  • 45
  • 134
    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. – Carl Smith Jul 09 '13 at 13:43
  • 33
    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? – John B Jun 23 '14 at 14:46
  • 48
    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. – abarnert Dec 03 '14 at 02:05
  • 33
    I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" with `if bool(len(li) == 0) is True:`? – augurar Jan 05 '15 at 19:40
  • 17
    @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. – ralokt Nov 19 '15 at 13:04
  • 9
    It is very bad to grab the length only to check for emptiness. This is not good in any way. – yo' Jan 07 '17 at 20:42
  • 10
    This is anti PEP 8 – jamylak Feb 17 '18 at 10:33
  • 11
    What if you *do* want to raise an exception for types without a `__len__`? This is perfect in that case. – BallpointBen May 10 '18 at 18:44
  • 6
    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. – Johan Jun 15 '18 at 05:51
  • 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) – Armstrongest Jun 07 '19 at 16:26
  • 4
    At least it won't say that `a` is empty for `a == None`, while `not a` would evaluate to `True` for `a == None`. – dzieciou May 30 '20 at 11:24
  • 5
    In my opinion, `not X` resolves to `True` for too many possible cases of `X`. Most notably, both the empty list and `None`. While a case where the value is either the empty list or `None` probably **should** not occur, I'm not confident that it **will** not occur. Especially when other people use parts of my code. Even though it's anti-PEP 8, I still prefer this approach. – Shiania White Aug 01 '20 at 16:48
  • 14
    @augurar: Addressing the idea that this is just making it needlessly more explicit, it's worth noting that `if bool(len(li) == 0) is True` does exactly the same thing as `if len(li) == 0`, and so there is no value in adding that additional code. However, `if len(li) == 0` certainly does do something different than `if li`. I think it's reasonable to argue that people should not code things in such a way that the latter comparison produces different results. However, the latter comparison **can** produce different results, where the former **cannot**, so I don't think this is a good argument. – Shiania White Aug 01 '20 at 16:56
  • @ShianiaWhite incorrect, this is a terrible way to check if a `len` of a list is empty or not. There is no need to calculate for `len` of a sequence to check its emptiness, python has already have our backs, it easily gives as the truth value of a sequence.. so doing `if l` is pretty much the best thing. Imagine almost a million size of a sequence, would we want to still waste our lives to get the `len`? Patrick's answer is the best one. – Ice Bear Dec 19 '20 at 15:13
  • 11
    @StackOffended The time complexity of `len` on list is O(1) and not O(n) as you might think. See [here](https://stackoverflow.com/questions/1115313/cost-of-len-function) for more info. – Jabba Dec 20 '20 at 18:57
  • 1
    oh that's great! that supports your argument, but I guess after 8 years of this topic doing `if a` would still be recommended & pythonic. – Ice Bear Dec 21 '20 at 00:54
  • 5
    @IceBear Use whichever you want. After 8 years I still prefer `len(a)`. – Jabba Dec 22 '20 at 17:15
  • 4
    As a developer who's come from C/C++, this especially hurts my brain and at first I found the first comment in this thread to be absurd. "Checking if the list is false"??? What's that all about. How is that at all clear to the programmer? I would expect something like `not None` to return `True` - that makes sense. But a list object? It has a type! It's not nothing. It's just a property of Python that (almost) all built-in types offer a pleasant boolean evaluation which makes sense in the context of the type and that needs to be respected to be a successful Pythonista. – Benjamin Crawford Ctrl-Alt-Tut Mar 10 '21 at 13:36
  • I would argue that `if not len(ls)` is probably better. But `if len(li) == 0:` is definitely better (more explicit, easier to read and it raises an error when using the wrong type) than `if not ls`. PEP 8 is anti-pythonic in this regard. – 12431234123412341234123 Sep 21 '21 at 10:00
  • 1
    @abarnert It SHOULD generate a error when you pass `None`, `False`, `0` or any other type that isn't some kind of list. – 12431234123412341234123 Sep 21 '21 at 10:06
  • if empty(list): looks like a good trade of between simplicity and explicity to me – Hedwin Bonnavaud Nov 23 '21 at 17:04
  • list_a=[1,2] if not(len(list_a)>0): print("List is empty") else: print("List not is empty") – Ali Hassan Mar 09 '22 at 09:45
  • 3
    Everybody here is out of line. This is clean, explicit, readable code. The minor addition of code lends clarity. – young_souvlaki Apr 12 '23 at 20:48
418

This is the first google hit for "python test empty array" and similar queries, and other people are generalizing the question beyond just lists, so here's a caveat for a different type of sequence that a lot of people 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

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

Mike
  • 19,114
  • 12
  • 59
  • 91
  • 89
    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. – Gareth Latty Feb 16 '15 at 20:47
  • 14
    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. – Mike Feb 16 '15 at 21:21
  • 29
    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. – Dalton Aug 20 '15 at 19:54
  • 1
    @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. – pydsigner Mar 10 '16 at 17:33
  • 2
    @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). – Mike Mar 10 '16 at 21:36
  • 1
    @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. – pydsigner Mar 10 '16 at 22:47
  • 1
    I'm not sure I get your point. If you `print(type(sub))` in your example you get `` -- 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. – Mike Mar 11 '16 at 00:23
  • 15
    This question has nothing to do with numpy arrays – pppery Jul 31 '17 at 18:58
  • 32
    @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. – peterhil Sep 12 '17 at 21:22
  • 1
    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](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.asarray.html). After that, you can proceed as in your answer without worrying about other formats. – Bas Swinckels Nov 09 '17 at 11:31
  • @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. – Mike Nov 09 '17 at 14:40
  • "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. – plugwash Sep 26 '18 at 21:47
  • 1
    @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. – Mike Sep 27 '18 at 18:16
  • @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 Feb 15 '20 at 19:01
  • @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 – Marco Sulla Feb 15 '20 at 19:04
  • 1
    If `len(zeros((1,0))` returned `0` then `len(zeros((2,2))` should return 4. There is the `size` method for that. If `array.shape` is `(2,3,4)` then `array[1].shape` is `(3,4)`, meaning that the first dimension works as a container for the trailing dimensions, etc, just like a nested list. So the expected result of `len(array)` for sure is `array.shape[0]`. And `zeros((1,0))` contains something: it contains 1 trailing dimension with extent 0. – Jonatan Öström Jul 06 '20 at 14:53
  • there is symple solution len(list( numpy.zeros((1,0))) ) instead of len( numpy.zeros((1,0)) ) – Bahae El Hmimdi May 12 '22 at 01:45
  • 1
    @BahaeElHmimdi That's a really bad "solution" because you actually make a copy of the data just to check its length. For more realistic examples, that can be a *lot* of data that you just don't need to copy. Another problem is that you have to know that you're dealing with a numpy array to do that extra step of converting to `list`. But if you already know that, you should just use the correct method: `if x.size`, which doesn't copy any data; it just checks a single pre-existing integer. And if you're unsure, it's far better to use dubiousjim's approach. – Mike May 12 '22 at 14:35
  • If I have an empty list mylist = [] then mylist.size doesn't work. – skan Dec 28 '22 at 20:34
  • 1
    @skan Right, that's why I said "the correct method in all cases *where you know you have a NumPy array* is to use `if x.size`" (emphasis added), and then said "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](https://stackoverflow.com/a/10835703/1194883)..." – Mike Dec 30 '22 at 02:12
363

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

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?

Explanation

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:

object.__bool__(self)

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.

and

object.__len__(self)

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))
0.13775854044661884
>>> min(timeit.repeat(lambda: [] == [], repeat=100))
0.0984637276455409
>>> min(timeit.repeat(lambda: not [], repeat=100))
0.07878462291455435

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

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.

Why?

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

PyVarObject

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 {
    PyObject_VAR_HEAD
    /* 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.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
  • 1
    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 Nov 28 '19 at 05:52
  • 1
    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. – Gregory Morse Nov 28 '19 at 06:31
  • 8
    Best answer so far, thanks! Pointing out the true logic of python with magicmethods and "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" is key. otherwise one falls down into "preferences" and never ends up with a proper conclusion. – ClementWalter Nov 17 '20 at 15:39
  • 2
    Great! This is the best answer! To anyone reading from 2020(it's December so it's almost 2021) and in the future. Doing `if l` is the "Pythonic" way and BEST way, as this guy explains it very well and also provided some sample code of the time performance calculated for every suggested answer which are `if len(a) == 0`, `if [] == []` and `if a` So clearly this (`if a`) is much faster & the one that must be practiced! – Ice Bear Dec 19 '20 at 15:22
  • You still don't explain why you should use `if ls` over `if len(ls)`. In 99%, i don't care about this small performance difference and prefer readability. `if len(ls)` is easier to read, more explicit and it trows an error when something is used that isn't some kind of list, this is why `if len(ls)` makes more sense. By the way i only get a about 15% performance difference between `not len([])` and `not []`. – 12431234123412341234123 Sep 21 '21 at 10:14
  • The idea is to use `if len(my_list) ...` because it fails when `my_list` isn't an object that supports `__len__`, to aid with troubleshooting typing issues? I suggest, instead, use a static type analysis engine like mypy. – Russia Must Remove Putin Sep 21 '21 at 15:18
  • I get that it's more efficient (thanks for clearly explaining that), but imho it's less robust. If something went wrong and `a` was e.g. `False` or 0, your code would wrongly say it was an empty list, and continue silently with that assumption (probably failing at some later and hard-to-debug point). `if len(a) == 0` would just fail with an error that pointed directly at where the problem was. Programming is often a tradeoff between efficiency and robustness, and sometimes choosing for efficiency is the right choice. But I wouldn't plainly state that `if not a` is _always_ the best option. – PieterNuyts Aug 10 '22 at 12:08
177

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

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

To Daren Thomas's answer:

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.

Jabba
  • 19,598
  • 6
  • 52
  • 45
Peter Hoffmann
  • 56,376
  • 15
  • 76
  • 59
  • 2
    Strange how `[] == False` will evaluate to False though – information_interchange Oct 14 '19 at 03:34
  • 7
    @information_interchange If you want to explicitly check the truthiness of a value, use `bool()`. `bool([]) == False` will evaluate to `True` as expected. – augurar Oct 20 '19 at 07:29
  • 1
    @information_interchange It really isn't. Consider that if `[] == False` evaluated to `True` then, for consistency, so should `0 == False` and `'' == False`, or even `'' == []`. Note that there's s distinction between truthiness in a boolean context and testing equality. IMHO Clojure does this right: only False and nil are falsy. Python's rule are reasonable. PHP used to have evil rules (haven't used that for a very long time, don't know now). – Paul Jun 09 '22 at 13:53
122

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.

Community
  • 1
  • 1
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 2
    "And when you violate those idioms, that's a strong signal." It can be a strong signal that you're simply working with code written by someone new to python, which is a lot of people – joel Jun 17 '20 at 12:19
107

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>

# <The 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:

a = []

if not a:
    # <React to empty list>

# <The rest of code>

is sufficient.

MrWonderful
  • 2,530
  • 1
  • 16
  • 22
  • 6
    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 `` 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. – Amarth Gûl Feb 02 '18 at 14:02
  • 2
    Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if :” 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 Feb 17 '18 at 19:18
  • 1
    @AmarthGûl - How might one *get* the results from the for loop to the script inside 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. – MrWonderful May 22 '18 at 22:45
  • 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.... – DJK Jun 24 '19 at 22:30
  • @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. – MrWonderful Jun 26 '19 at 00:14
  • 1
    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 – DJK Jun 26 '19 at 02:21
  • 12
    @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. – MrWonderful Jun 27 '19 at 04:07
  • 3
    Good answer, but `!a` is a syntax error. It should be `not a`. – PieterNuyts Aug 10 '22 at 12:12
  • @PieterNuyts - Indeed it is. Fixed & thank you! – MrWonderful Sep 28 '22 at 20:31
  • Why check - when the list changes (is appended or popped from) within the block, it seems to not update in the condition check... I was running with AREPL VSCode extension, with Python 3.11 – user8395964 Apr 13 '23 at 08:05
  • @user8395964 - Indeed, iterating over a list while modifying it is not considered 'best practice', or even 'acceptable practice' where I've worked in the past. See https://stackoverflow.com/questions/1637807/modifying-list-while-iterating for details. – MrWonderful Apr 18 '23 at 19:03
  • i suppose then that the DSA algorithms (bfs, etc) don't care about best practices lol – user8395964 Apr 19 '23 at 08:14
  • @user8395964 - I'm afraid I'm not understanding your point. Is there a problem with the DSA algorithms that you are attempting to debug? Is your question about iterating over a list being modified? The OP's question is how to check for an empty list and my answer is meant to be sufficient for all users, likely including you, as the last statement is "If you do actually need to check the array for emptiness...", which should cover your case and any others. Otherwise, please include an example. Thanks. – MrWonderful Apr 24 '23 at 14:23
76

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
George V. Reilly
  • 15,885
  • 7
  • 43
  • 38
53

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.

Mike
  • 19,114
  • 12
  • 59
  • 91
dubiousjim
  • 4,722
  • 1
  • 36
  • 34
  • 3
    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 `collections.abc.Sized` or `collections.abc.Sequence`, 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. – abarnert Dec 03 '14 at 02:09
  • 14
    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. – Gareth Latty Feb 16 '15 at 20:54
  • 1
    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. – RemcoGerlich Jul 16 '15 at 13:10
  • 2
    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 == []`. – dubiousjim Jul 16 '15 at 13:36
  • @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." – MrWonderful Oct 12 '18 at 04:47
  • Instead of manually checking types you should use [type hinting](https://docs.python.org/library/typing.html) (introduced in 3.5). – Boris Verkhovskiy May 11 '19 at 07:07
  • 1
    @Boris Type hints help static type checkers (like mypy) to check for type correctness but do not perform runtime type checking. – Tim Jul 10 '19 at 02:10
  • Is there a reason to prefer `.size` over `.ndim > 0`? I just hit a case where `a=np.array(None)`. `a.size` is 1, but `a.ndim` is 0. `for _ in a:` gives "TypeError: iteration over a 0-d array" – craq Apr 13 '23 at 03:36
  • The proper way to have runtime typechecking is thus to use [beartype](https://github.com/beartype/beartype) – JWCS Aug 06 '23 at 00:03
38

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наđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
  • @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()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIsInstance). – Sнаđошƒаӽ Sep 01 '18 at 05:39
37

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

try:
    next(iter(a))
    # list has elements
except StopIteration:
    print("Error: a is empty")
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
37

I prefer the following:

if a == []:
   print "The list is empty."
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
verix
  • 1,703
  • 2
  • 15
  • 12
  • 52
    This is going to be slower, as you instantiate an extra empty list unnecessarily. – Carl Meyer Sep 10 '08 at 13:42
  • 43
    this is less readable than `if not a:` and breaks more easily. Please don't do it. – devsnd Nov 12 '12 at 11:23
  • 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. – A Star Mar 16 '19 at 21:03
  • 8
    "breaks more easily" citation needed? `if not a` breaks when a is `None` - you may *desire* the same behaviour for `None` and `[]`, but if you *explicitly* want to check for an empty list, `if not a` doesn't do that. – scubbo Aug 20 '20 at 16:14
  • 1
    @scubbo if you really want to explicitly check whether it's an empty list or not, consider using `isinstance(a, list) and not a` instead. – AboodXD Apr 22 '21 at 10:59
31

Method 1 (preferred):

if not a:
   print ("Empty")

Method 2:

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

Method 3:

if a == []:
  print ("Empty")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikrant
  • 1,149
  • 12
  • 19
25

You can even try using bool() like this. Although it is less readable surely it's a concise way to perform 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 the checking list is empty or not.

Very handy and useful.

Sunil Lulla
  • 797
  • 10
  • 18
  • 8
    For those (like me) who didn't know, `bool()` converts a Python variable into a boolean so you can [store the truthiness or falsiness](http://stackoverflow.com/a/24868176/6157047) 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. – Galen Long Mar 10 '17 at 21:42
  • This is usable in an expression and is more terse. – qneill Dec 18 '17 at 21:13
  • 1
    The downside happens when `a is None`. This is often acceptable, just good to be aware of. – Lars P Sep 29 '20 at 19:26
19

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):
    return len(list1) == 0

list1 = []

if enquiry(list1):
    print("The list isn't empty")
else:
    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):
    return not list1

list1 = []

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

# Result: "The list is Empty"
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
18
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))

list_test(None)
list_test([])
list_test([1,2,3])

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

list_test2(None)
list_test2([])
list_test2([1,2,3])

produces expected

list is empty
list is empty
list has 3 elements
Tagar
  • 13,911
  • 6
  • 95
  • 110
  • 1
    IMHO, this is this best answer. It addresses the nuances with respect to `None` and `[]` (an empty list) when testing. – HighExodus Nov 24 '20 at 15:59
15

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
    else:
        return all(bool(x) for x in l)

Now you can use:

if empty_list(lst):
    # do your stuff.
Corman
  • 749
  • 11
  • 16
Rahul
  • 10,830
  • 4
  • 53
  • 88
15

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")
HackerBoss
  • 829
  • 7
  • 16
  • 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 '...'` – Sven-Eric Krüger Jan 10 '19 at 09:40
  • 9
    @SvenKrüger nope. Operator `and` is lazy in Python. Nothing after `and` is going to be executed if condition before `and` is False. – ElmoVanKielmo Feb 26 '19 at 14:00
13
print('not empty' if a else 'empty')

a little more practical:

a.pop() if a else None

and the shortest version:

if a: a.pop() 
Nice18
  • 476
  • 2
  • 12
Andrey Topoleov
  • 1,591
  • 15
  • 20
11

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

Test:

>>> is_empty('sss')
False
>>> is_empty(555)
False
>>> is_empty(0)
False
>>> is_empty('')
True
>>> is_empty([3])
False
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(())
True
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27
  • 2
    Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable. – pppery Jul 12 '17 at 15:47
  • 1
    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.) – Davis Herring Sep 20 '17 at 02:40
11

We could use a simple if else:

item_list=[]
if len(item_list) == 0:
    print("list is empty")
else:
    print("list is not empty")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
l. zhang
  • 335
  • 3
  • 5
  • 5
    -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. – MrWonderful Apr 29 '19 at 09:08
8

Simply use is_empty() or make function like:-

def is_empty(any_structure):
    if any_structure:
        print('Structure is not empty.')
        return True
    else:
        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).

Vineet Jain
  • 1,515
  • 4
  • 21
  • 31
  • 3
    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 Sep 20 '17 at 02:39
  • 4
    Why do we want a variation on `bool` that (also) prints messages to standard output? – Davis Herring Sep 20 '17 at 03:13
  • @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. – Vineet Jain Sep 20 '17 at 03:45
8

Simple way is checking the length is equal zero.

if len(a) == 0:
    print("a is empty")
Ashiq Imran
  • 2,077
  • 19
  • 17
7

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

Trect
  • 2,759
  • 2
  • 30
  • 35
6

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

Vukašin Manojlović
  • 3,717
  • 3
  • 19
  • 31
figs_and_nuts
  • 4,870
  • 2
  • 31
  • 56
6

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.

ifconfig
  • 6,242
  • 7
  • 41
  • 65
Vedran Šego
  • 3,553
  • 3
  • 27
  • 40