For example, if passed the following:
a = []
How do I check to see if a
is empty?
27 Answers 27
if not a:
print("List is empty")
Using the implicit booleanness of the empty list
is quite Pythonic.
-
1575Playing 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– James McMahon11/22/2011 06:14:02Commented Nov 22, 2011 at 6:14
-
290@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 (() == []
isFalse
). here, general consensus seems to be that duck typing wins out (in effect, saying that__nonzero__
is the interface for testing emptiness docs.python.org/reference/datamodel.html#object.__nonzero__)andrew cooke– andrew cooke05/31/2012 14:50:08Commented May 31, 2012 at 14:50 -
137This 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– Mr.WorshipMe03/20/2019 18:01:33Commented Mar 20, 2019 at 18:01
-
14@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– Brennen Sprimont04/14/2019 04:52:39Commented Apr 14, 2019 at 4:52
-
124Coming from a language that claims to be some sort of poetry, this mechanism is pure garbage. Semantically, being empty is very different to not beingEdwin Rodríguez– Edwin Rodríguez04/04/2020 14:03:17Commented Apr 4, 2020 at 14:03
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):
-
135The second way seems better if you wish to signal that
seq
is expected to be some sort of list-like object.BallpointBen– BallpointBen05/10/2018 18:44:42Commented May 10, 2018 at 18:44 -
22@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possibleaxolotl– axolotl07/14/2018 05:35:39Commented Jul 14, 2018 at 5:35
-
16@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.user3064538– user306453801/04/2019 23:46:56Commented Jan 4, 2019 at 23:46
-
23numpy 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– Mr.WorshipMe03/20/2019 18:03:33Commented Mar 20, 2019 at 18:03
-
25Despite all Pythonic advocates, I am with @BallpointBen in that if you mistakenly wrote
seq = [0]
asseq = 0
,len(seq)
will help you catch the error. To err is human. So is a programmer.aafulei– aafulei09/26/2019 02:34:34Commented Sep 26, 2019 at 2:34
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.
-
137Checking 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 Younger– Carl Younger07/09/2013 13:43:53Commented Jul 9, 2013 at 13:43 -
35This 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– John B06/23/2014 14:46:46Commented Jun 23, 2014 at 14:46
-
50Anyway, 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
or0
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– abarnert12/03/2014 02:05:52Commented Dec 3, 2014 at 2:05 -
34I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" with
if bool(len(li) == 0) is True:
?augurar– augurar01/05/2015 19:40:05Commented Jan 5, 2015 at 19:40 -
22@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 asif len(li) == 0
, and so there is no value in adding that additional code. However,if len(li) == 0
certainly does do something different thanif 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– Shiania White08/01/2020 16:56:15Commented Aug 1, 2020 at 16:56
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 list
s 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 bool
s, and if x
tries to evaluate all of those bool
s 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.
-
94It'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 thatpathlib
uses/
to concatenate paths instead of+
- it's non-standard, but makes sense in context.Gareth Latty– Gareth Latty02/16/2015 20:47:12Commented Feb 16, 2015 at 20:47 -
14Agreed. 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
andlen(x)
idioms -- and sometimes that breakage can be very hard to detect and debug.Mike– Mike02/16/2015 21:21:02Commented Feb 16, 2015 at 21:21 -
30I 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– Dalton08/20/2015 19:54:14Commented Aug 20, 2015 at 19:54
-
15This question has nothing to do with numpy arraysPerry– Perry07/31/2017 18:58:37Commented Jul 31, 2017 at 18:58
-
35@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– peterhil09/12/2017 21:22:04Commented Sep 12, 2017 at 21:22
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 returnsFalse
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
andFalse
.- 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 returnFalse
orTrue
. 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
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
This is an extension of
PyObject
that adds theob_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 thePyObject_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 enjoynot not l
despite triple the speed. It looks ridiculous. But the speed wins out
I suppose the problem is testing with timeit since justif 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.
-
1I 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 enjoynot not l
despite triple the speed. It looks ridiculous. But the speed wins outGregory Morse– Gregory Morse11/28/2019 05:52:15Commented Nov 28, 2019 at 5:52 -
1I 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– Gregory Morse11/28/2019 06:31:53Commented Nov 28, 2019 at 6:31 -
10Best 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– ClementWalter11/17/2020 15:39:32Commented Nov 17, 2020 at 15:39
-
2Great! 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 areif len(a) == 0
,if [] == []
andif a
So clearly this (if a
) is much faster & the one that must be practiced!Ice Bear– Ice Bear12/19/2020 15:22:07Commented Dec 19, 2020 at 15:22 -
1I 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 thatif not a
is always the best option.PieterNuyts– PieterNuyts08/10/2022 12:08:14Commented Aug 10, 2022 at 12:08
An empty list is itself considered false in true value testing (see python documentation):
a = []
if a:
print("not empty")
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.
-
2Strange how
[] == False
will evaluate to False thoughinformation_interchange– information_interchange10/14/2019 03:34:00Commented Oct 14, 2019 at 3:34 -
7@information_interchange If you want to explicitly check the truthiness of a value, use
bool()
.bool([]) == False
will evaluate toTrue
as expected.augurar– augurar10/20/2019 07:29:08Commented Oct 20, 2019 at 7:29 -
1@information_interchange It really isn't. Consider that if
[] == False
evaluated toTrue
then, for consistency, so should0 == 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– Paul06/09/2022 13:53:56Commented Jun 9, 2022 at 13:53
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.
-
3"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 peoplejoel– joel06/17/2020 12:19:36Commented Jun 17, 2020 at 12:19
-
I was about to rebut "Following those idioms makes your code easier to read for anyone experienced in Python." - Yes, but clean code is accessible to an even larger audience. Thanks @joel for picking that up as well, on the following sentence :)Rick Moritz– Rick Moritz12/07/2023 11:03:55Commented Dec 7, 2023 at 11:03
Why check at all?
Before checking if a list is empty, one should consider whether it's necessary. Python's idiomatic approach often avoids explicit checks in favor of letting the language handle such cases naturally.
For example:
a = []
for item in a:
# <Do something with item>
# <The rest of code>
If a is empty, the body of the loop simply won't execute, and the program will continue gracefully. This approach is often the simplest and most Pythonic way to handle lists, regardless of their contents.
However, if you DO specifically need to check for an empty list (e.g., to handle it differently):
a = []
if not a:
# <React to empty list>
# <The rest of code>
is sufficient, as others have suggested.
-
7The 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 thefor
loop? Or directly use some values ina
? 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– Amarth Gûl02/02/2018 14:02:48Commented Feb 2, 2018 at 14:02 -
2Respectfully, 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– MrWonderful02/17/2018 19:18:43Commented Feb 17, 2018 at 19:18
-
1@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.MrWonderful– MrWonderful05/22/2018 22:45:27Commented May 22, 2018 at 22:45
-
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– MrWonderful06/27/2019 04:07:53Commented Jun 27, 2019 at 4:07
-
3Good answer, but
!a
is a syntax error. It should benot a
.PieterNuyts– PieterNuyts08/10/2022 12:12:51Commented Aug 10, 2022 at 12:12
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.
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.
-
3It'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
orcollections.abc.Sequence
, but it might be one you write yourself andregister(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– abarnert12/03/2014 02:09:53Commented Dec 3, 2014 at 2:09 -
15The 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– Gareth Latty02/16/2015 20:54:10Commented Feb 16, 2015 at 20:54
-
1If you really want to check that the value is exactly
[]
and not something falsy of another type, then surelyif a == []:
is called for, rather than mucking about with isinstance.RemcoGerlich– RemcoGerlich07/16/2015 13:10:54Commented Jul 16, 2015 at 13:10 -
2There are some automatic coercions for
==
though. Off the top of my head, I can't identify any for[]
.[] == ()
for instance returnsFalse
. But for examplefrozenset()==set()
returnsTrue
. So it's worth at least giving some thought to whether some undesired type might be coerced to[]
(or vice versa) when doinga == []
.dubiousjim– dubiousjim07/16/2015 13:36:41Commented Jul 16, 2015 at 13:36 -
1@Boris Type hints help static type checkers (like mypy) to check for type correctness but do not perform runtime type checking.Tim– Tim07/10/2019 02:10:17Commented Jul 10, 2019 at 2:10
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 valueFalse
.
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!')
-
@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 alist
, you can useassertIsInstance()
.Sнаđошƒаӽ– Sнаđошƒаӽ09/01/2018 05:39:51Commented Sep 1, 2018 at 5:39
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")
I prefer the following:
if a == []:
print "The list is empty."
-
52This is going to be slower, as you instantiate an extra empty list unnecessarily.Carl Meyer– Carl Meyer09/10/2008 13:42:00Commented Sep 10, 2008 at 13:42
-
43this is less readable than
if not a:
and breaks more easily. Please don't do it.devsnd– devsnd11/12/2012 11:23:26Commented Nov 12, 2012 at 11:23 -
There is a good point made earlier
() == []
is also equal to false. Although I like how this implementation reads theif not a:
covers all cases, if you are definitely expecting a list then your example should be sufficient.A Star– A Star03/16/2019 21:03:31Commented Mar 16, 2019 at 21:03 -
8"breaks more easily" citation needed?
if not a
breaks when a isNone
- you may desire the same behaviour forNone
and[]
, but if you explicitly want to check for an empty list,if not a
doesn't do that.scubbo– scubbo08/20/2020 16:14:57Commented Aug 20, 2020 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– AboodXD04/22/2021 10:59:44Commented Apr 22, 2021 at 10:59
Method 1 (preferred):
if not a:
print ("Empty")
Method 2:
if len(a) == 0:
print("Empty")
Method 3:
if a == []:
print ("Empty")
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.
-
9For 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.Galen Long– Galen Long03/10/2017 21:42:15Commented Mar 10, 2017 at 21:42 -
1This is usable in an expression and is more terse.qneill– qneill12/18/2017 21:13:24Commented Dec 18, 2017 at 21:13
-
2The downside happens when
a is None
. This is often acceptable, just good to be aware of.Lars P– Lars P09/29/2020 19:26:25Commented Sep 29, 2020 at 19:26
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"
-
1Upvoted for also showing how to check if it is not empty! This helps cover the opposite but equally important use caseDavid Frick– David Frick08/16/2020 17:01:41Commented Aug 16, 2020 at 17:01
-
2Note the second one may not work with other common array type objects such as numpy arrays.Alexis Drakopoulos– Alexis Drakopoulos02/02/2021 11:11:56Commented Feb 2, 2021 at 11:11
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
-
1IMHO, this is this best answer. It addresses the nuances with respect to
None
and[]
(an empty list) when testing.HighExodus– HighExodus11/24/2020 15:59:37Commented Nov 24, 2020 at 15: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")
-
It is possible this throws an exception, if
a
is not a list anda
has no method__len__
implemented. I would recommend:if isinstance(obj, list): if len(obj) == 0: print '...'
Sven-Eric Krüger– Sven-Eric Krüger01/10/2019 09:40:10Commented Jan 10, 2019 at 9:40 -
9@SvenKrüger nope. Operator
and
is lazy in Python. Nothing afterand
is going to be executed if condition beforeand
is False.ElmoVanKielmo– ElmoVanKielmo02/26/2019 14:00:29Commented Feb 26, 2019 at 14:00
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.
-
2all(bool(x) for x in l) is True for an empty listgberger– gberger03/05/2018 17:27:17Commented Mar 5, 2018 at 17:27
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()
We could use a simple if else:
item_list=[]
if len(item_list) == 0:
print("list is empty")
else:
print("list is not empty")
-
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– MrWonderful04/29/2019 09:08:52Commented Apr 29, 2019 at 9:08
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
-
2Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.Perry– Perry07/12/2017 15:47:09Commented Jul 12, 2017 at 15:47
-
1If I wasn't happy with
if a:
, it would be because I wanted an exception ifa
wasn't some sort of container. (Being an iterable also allows iterators, which can't usefully be tested for emptiness.)Davis Herring– Davis Herring09/20/2017 02:40:33Commented Sep 20, 2017 at 2:40
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)
.
-
3The name
is_empty
suggests that it returns something. But if it did, that something would just bebool(any_structure)
, which you should use instead (when you need abool
at all).Davis Herring– Davis Herring09/20/2017 02:39:05Commented Sep 20, 2017 at 2:39 -
4Why do we want a variation on
bool
that (also) prints messages to standard output?Davis Herring– Davis Herring09/20/2017 03:13:03Commented Sep 20, 2017 at 3: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– Vineet Jain09/20/2017 03:45:30Commented Sep 20, 2017 at 3:45
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
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
-
2please give more explanation about how it is working without writing "if"?GD- Ganesh Deshmukh– GD- Ganesh Deshmukh12/30/2018 10:48:00Commented Dec 30, 2018 at 10:48
-
4This is not pythonic nor a complete example. Also, It instantiates an empty list every time it is encountered. Don't do this.MrWonderful– MrWonderful04/29/2019 08:53:32Commented Apr 29, 2019 at 8:53
-
2@MrWonderful it does not instantiate an empty list every time. It just verifies if the existing list
a
is empty or not.Trect– Trect04/06/2020 15:44:54Commented Apr 6, 2020 at 15:44 -
2@MrWonderful I don't get what makes it
pythonic
Trect– Trect04/06/2020 15:45:29Commented Apr 6, 2020 at 15:45 -
1@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 asif(a==[])
Trect– Trect04/06/2020 15:47:07Commented Apr 6, 2020 at 15:47
The truth value of an empty list is False
whereas for a non-empty list it is True
.
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.