How do I check if a list is empty?
For example, if passed the following:
a =
How do I check to see if a is empty?
python list
add a comment |
For example, if passed the following:
a =
How do I check to see if a is empty?
python list
add a comment |
For example, if passed the following:
a =
How do I check to see if a is empty?
python list
For example, if passed the following:
a =
How do I check to see if a is empty?
python list
python list
edited Nov 18 '18 at 11:13
ayhan
37.2k669105
37.2k669105
asked Sep 10 '08 at 6:20
Ray VegaRay Vega
80.8k91199191
80.8k91199191
add a comment |
add a comment |
36 Answers
36
active
oldest
votes
1 2
next
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite pythonic.
857
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 6:14
169
@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 likeif 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
May 31 '12 at 14:50
3
Alternatively, one can useif len(a) == 0: print('List is empty')
– thepunitsingh
Jan 11 at 10:31
add a comment |
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
14
The second way seems better if you wish to signal thatseqis expected to be some sort of list-like object.
– BallpointBen
May 10 '18 at 18:44
2
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
add a comment |
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.
54
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 thinkliis a bool at all, and wont care. If it's important, you should add a comment, not more code.
– Carl Smith
Jul 9 '13 at 13:43
11
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
24
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 wantNoneor0to 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 3 '14 at 2:05
10
I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" withif bool(len(li) == 0) is True:?
– augurar
Jan 5 '15 at 19:40
10
@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
|
show 5 more comments
Other people seem to be generalizing the question beyond just lists, so I thought I'd add a caveat for a different type of sequence that a lot of people might use, especially since this is the first google hit for "python test empty array".
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.
29
It's worth noting that this isn't a flaw in Python, but rather an intentional break of contract bynumpy-numpyis 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 thatpathlibuses/to concatenate paths instead of+- it's non-standard, but makes sense in context.
– Gareth Latty
Feb 16 '15 at 20:47
8
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 commonif xandlen(x)idioms -- and sometimes that breakage can be very hard to detect and debug.
– Mike
Feb 16 '15 at 21:21
13
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
8
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
11
@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
|
show 8 more comments
An empty list is itself considered false in true value testing (see python documentation):
a =
if a:
print "not empty"
@Daren Thomas
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.
add a comment |
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')
Appeal to Authority
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 returnsFalseor 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:
NoneandFalse.
- 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 returnFalseorTrue. 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
PyObjectthat adds theob_sizefield. 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_HEADmacro.
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
I have enjoyed researching this and I spend a lot of time curating my answers. If you think I'm leaving something out, please let me know in a comment.
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
4
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
add a comment |
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.
add a comment |
I have seen the below as preferred:
if not a:
print("The list is empty or null")
3
Noneis not a list; it is its own type.
– Yann Vernier
Jan 31 '18 at 9:25
add a comment |
Why check at all?
No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.
I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
a =
for item in a:
<do something with item>
<rest of code>
This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient.
1
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside<rest of code>that might use the result from theforloop? 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
Feb 2 '18 at 14:02
1
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
@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
May 22 '18 at 22:45
add a comment |
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.
add a comment |
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.
2
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, likecollections.abc.Sizedorcollections.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
Dec 3 '14 at 2:09
11
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 exactlyand not something falsy of another type, then surelyif 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 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
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 4:47
add a comment |
Python is very uniform about the treatment of emptiness. Given the following:
a =
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
add a comment |
From documentation on truth value testing:
All values other than what is listed here are considered True
NoneFalse- 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!')
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
@DJ_Stuffy_K assert what in unit testing, an empty list? Just useassert(not myList). If you also want to assert the object is alist, you can useassertIsInstance().
– Sнаđошƒаӽ
Sep 1 '18 at 5:39
add a comment |
Some methods that I use:
if not a:
print "list is empty"
if len(a) == 0:
print "list is empty"
add a comment |
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")
add a comment |
I prefer the following:
if a == :
print "The list is empty."
26
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
22
this is less readable thanif not a:and breaks more easily. Please don't do it.
– devsnd
Nov 12 '12 at 11:23
add a comment |
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
add a comment |
Another simple way could be
a =
if len(a) == 0:
print("Empty")
else:
print(" Not empty")
add a comment |
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
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
add a comment |
You can check if the length of the array is zero (or not.) If the length of the array is zero, then it is empty. try the following:
a =
if len(a)==0 : print "List is empty"
Using%timeitin ipdb,len(a)is almost 50% faster thanbool(a), however pep 8 would recommend usingbool(a).
– raratiru
Dec 21 '18 at 18:42
add a comment |
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
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
1
If I wasn't happy withif a:, it would be because I wanted an exception ifawasn'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 2:40
add a comment |
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, ifais not a list andahas no method__len__implemented. I would recommend:if isinstance(obj, list): if len(obj) == 0: print '...'
– Sven Krüger
Jan 10 at 9:40
add a comment |
we could use a simple if else:
list=
if len(list)==0:
print ("list is empty")
else:
print ("list is not empty")
add a comment |
You can even try using bool() like this
a = [1,2,3];
print bool(a); # it will return True
a = ;
print bool(a); # it will return False
I love this way for checking list is empty or not.
Very handy and useful.
4
For those (like me) who didn't know,bool()converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.
– 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
add a comment |
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
add a comment |
print('not empty' if a else 'empty')
a little more practical:
a.pop() if a else None
add a comment |
Check if: len(list) == 0 returns: True
I see that pylint complains about this:>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214it is way slower
– MortenB
Feb 8 at 10:18
add a comment |
Method 1 (Preferred):
if not a :
print ("Empty")
Method 2 :
if len(a) == 0 :
print( "Empty" )
Method 3:
if a == :
print ("Empty")
add a comment |
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).
3
The nameis_emptysuggests that it returns something. But if it did, that something would just bebool(any_structure), which you should use instead (when you need aboolat all).
– Davis Herring
Sep 20 '17 at 2:39
2
Why do we want a variation onboolthat (also) prints messages to standard output?
– Davis Herring
Sep 20 '17 at 3:13
@DavisHerring We always have two choice first is to print using function other is using returnboolvariable. Choice is yours. I write both so you can choose between them.
– Vineet Jain
Sep 20 '17 at 3:45
add a comment |
If you want to check if list is empty;
l =
if l:
# do your stuff.
If you want to check weather all the values in list is empty.
l = ["", False, 0, '', , {}, ()]
if all(bool(x) for x in l):
# do your stuff.
However this will be True for empty list.
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.
1
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
add a comment |
1 2
next
protected by Srikar Appalaraju Feb 22 '13 at 8:10
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
36 Answers
36
active
oldest
votes
36 Answers
36
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite pythonic.
857
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 6:14
169
@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 likeif 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
May 31 '12 at 14:50
3
Alternatively, one can useif len(a) == 0: print('List is empty')
– thepunitsingh
Jan 11 at 10:31
add a comment |
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite pythonic.
857
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 6:14
169
@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 likeif 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
May 31 '12 at 14:50
3
Alternatively, one can useif len(a) == 0: print('List is empty')
– thepunitsingh
Jan 11 at 10:31
add a comment |
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite pythonic.
if not a:
print("List is empty")
Using the implicit booleanness of the empty list is quite pythonic.
edited Apr 27 '17 at 2:52
answered Sep 10 '08 at 6:28
PatrickPatrick
59.4k104561
59.4k104561
857
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 6:14
169
@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 likeif 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
May 31 '12 at 14:50
3
Alternatively, one can useif len(a) == 0: print('List is empty')
– thepunitsingh
Jan 11 at 10:31
add a comment |
857
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 6:14
169
@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 likeif 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
May 31 '12 at 14:50
3
Alternatively, one can useif len(a) == 0: print('List is empty')
– thepunitsingh
Jan 11 at 10:31
857
857
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 6:14
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 6:14
169
169
@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 docs.python.org/reference/datamodel.html#object.__nonzero__)– andrew cooke
May 31 '12 at 14:50
@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 docs.python.org/reference/datamodel.html#object.__nonzero__)– andrew cooke
May 31 '12 at 14:50
3
3
Alternatively, one can use
if len(a) == 0: print('List is empty')– thepunitsingh
Jan 11 at 10:31
Alternatively, one can use
if len(a) == 0: print('List is empty')– thepunitsingh
Jan 11 at 10:31
add a comment |
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
14
The second way seems better if you wish to signal thatseqis expected to be some sort of list-like object.
– BallpointBen
May 10 '18 at 18:44
2
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
add a comment |
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
14
The second way seems better if you wish to signal thatseqis expected to be some sort of list-like object.
– BallpointBen
May 10 '18 at 18:44
2
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
add a comment |
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
edited Mar 26 '18 at 17:17
David Moles
18.9k18105179
18.9k18105179
answered Sep 10 '08 at 10:33
Harley HolcombeHarley Holcombe
113k146362
113k146362
14
The second way seems better if you wish to signal thatseqis expected to be some sort of list-like object.
– BallpointBen
May 10 '18 at 18:44
2
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
add a comment |
14
The second way seems better if you wish to signal thatseqis expected to be some sort of list-like object.
– BallpointBen
May 10 '18 at 18:44
2
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
14
14
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
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
2
2
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen which, Pythonism advocates would say, should be implicit in the way the variable is named, as much as possible
– Aalok
Jul 14 '18 at 5:35
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
@BallpointBen try using Python's type hinting for signaling what a variable should be. It was introduced in 3.5.
– Boris
Jan 4 at 23:46
add a comment |
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.
54
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 thinkliis a bool at all, and wont care. If it's important, you should add a comment, not more code.
– Carl Smith
Jul 9 '13 at 13:43
11
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
24
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 wantNoneor0to 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 3 '14 at 2:05
10
I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" withif bool(len(li) == 0) is True:?
– augurar
Jan 5 '15 at 19:40
10
@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
|
show 5 more comments
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.
54
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 thinkliis a bool at all, and wont care. If it's important, you should add a comment, not more code.
– Carl Smith
Jul 9 '13 at 13:43
11
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
24
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 wantNoneor0to 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 3 '14 at 2:05
10
I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" withif bool(len(li) == 0) is True:?
– augurar
Jan 5 '15 at 19:40
10
@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
|
show 5 more comments
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.
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.
edited Sep 9 '17 at 4:04
Aaron Hall♦
175k51305253
175k51305253
answered Sep 5 '11 at 0:30
JabbaJabba
10.3k33736
10.3k33736
54
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 thinkliis a bool at all, and wont care. If it's important, you should add a comment, not more code.
– Carl Smith
Jul 9 '13 at 13:43
11
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
24
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 wantNoneor0to 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 3 '14 at 2:05
10
I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" withif bool(len(li) == 0) is True:?
– augurar
Jan 5 '15 at 19:40
10
@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
|
show 5 more comments
54
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 thinkliis a bool at all, and wont care. If it's important, you should add a comment, not more code.
– Carl Smith
Jul 9 '13 at 13:43
11
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
24
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 wantNoneor0to 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 3 '14 at 2:05
10
I think this is just needlessly lengthening the code. Otherwise, why not be even more "explicit" withif bool(len(li) == 0) is True:?
– augurar
Jan 5 '15 at 19:40
10
@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
54
54
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 9 '13 at 13:43
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 9 '13 at 13:43
11
11
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
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
24
24
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 3 '14 at 2:05
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 3 '14 at 2:05
10
10
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 5 '15 at 19:40
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 5 '15 at 19:40
10
10
@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
@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
|
show 5 more comments
Other people seem to be generalizing the question beyond just lists, so I thought I'd add a caveat for a different type of sequence that a lot of people might use, especially since this is the first google hit for "python test empty array".
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.
29
It's worth noting that this isn't a flaw in Python, but rather an intentional break of contract bynumpy-numpyis 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 thatpathlibuses/to concatenate paths instead of+- it's non-standard, but makes sense in context.
– Gareth Latty
Feb 16 '15 at 20:47
8
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 commonif xandlen(x)idioms -- and sometimes that breakage can be very hard to detect and debug.
– Mike
Feb 16 '15 at 21:21
13
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
8
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
11
@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
|
show 8 more comments
Other people seem to be generalizing the question beyond just lists, so I thought I'd add a caveat for a different type of sequence that a lot of people might use, especially since this is the first google hit for "python test empty array".
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.
29
It's worth noting that this isn't a flaw in Python, but rather an intentional break of contract bynumpy-numpyis 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 thatpathlibuses/to concatenate paths instead of+- it's non-standard, but makes sense in context.
– Gareth Latty
Feb 16 '15 at 20:47
8
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 commonif xandlen(x)idioms -- and sometimes that breakage can be very hard to detect and debug.
– Mike
Feb 16 '15 at 21:21
13
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
8
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
11
@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
|
show 8 more comments
Other people seem to be generalizing the question beyond just lists, so I thought I'd add a caveat for a different type of sequence that a lot of people might use, especially since this is the first google hit for "python test empty array".
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.
Other people seem to be generalizing the question beyond just lists, so I thought I'd add a caveat for a different type of sequence that a lot of people might use, especially since this is the first google hit for "python test empty array".
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.
edited Nov 9 '17 at 16:05
answered Feb 21 '12 at 16:48
MikeMike
9,73663867
9,73663867
29
It's worth noting that this isn't a flaw in Python, but rather an intentional break of contract bynumpy-numpyis 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 thatpathlibuses/to concatenate paths instead of+- it's non-standard, but makes sense in context.
– Gareth Latty
Feb 16 '15 at 20:47
8
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 commonif xandlen(x)idioms -- and sometimes that breakage can be very hard to detect and debug.
– Mike
Feb 16 '15 at 21:21
13
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
8
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
11
@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
|
show 8 more comments
29
It's worth noting that this isn't a flaw in Python, but rather an intentional break of contract bynumpy-numpyis 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 thatpathlibuses/to concatenate paths instead of+- it's non-standard, but makes sense in context.
– Gareth Latty
Feb 16 '15 at 20:47
8
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 commonif xandlen(x)idioms -- and sometimes that breakage can be very hard to detect and debug.
– Mike
Feb 16 '15 at 21:21
13
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
8
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
11
@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
29
29
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
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
8
8
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
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
13
13
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
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
8
8
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
This question has nothing to do with numpy arrays
– ppperry
Jul 31 '17 at 18:58
11
11
@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
@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
|
show 8 more comments
An empty list is itself considered false in true value testing (see python documentation):
a =
if a:
print "not empty"
@Daren Thomas
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.
add a comment |
An empty list is itself considered false in true value testing (see python documentation):
a =
if a:
print "not empty"
@Daren Thomas
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.
add a comment |
An empty list is itself considered false in true value testing (see python documentation):
a =
if a:
print "not empty"
@Daren Thomas
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.
An empty list is itself considered false in true value testing (see python documentation):
a =
if a:
print "not empty"
@Daren Thomas
EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?
Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.
edited Sep 6 '14 at 1:29
twasbrillig
6,55242552
6,55242552
answered Sep 10 '08 at 6:31
Peter HoffmannPeter Hoffmann
34.8k116556
34.8k116556
add a comment |
add a comment |
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')
Appeal to Authority
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 returnsFalseor 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:
NoneandFalse.
- 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 returnFalseorTrue. 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
PyObjectthat adds theob_sizefield. 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_HEADmacro.
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
I have enjoyed researching this and I spend a lot of time curating my answers. If you think I'm leaving something out, please let me know in a comment.
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
4
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
add a comment |
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')
Appeal to Authority
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 returnsFalseor 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:
NoneandFalse.
- 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 returnFalseorTrue. 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
PyObjectthat adds theob_sizefield. 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_HEADmacro.
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
I have enjoyed researching this and I spend a lot of time curating my answers. If you think I'm leaving something out, please let me know in a comment.
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
4
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
add a comment |
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')
Appeal to Authority
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 returnsFalseor 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:
NoneandFalse.
- 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 returnFalseorTrue. 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
PyObjectthat adds theob_sizefield. 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_HEADmacro.
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
I have enjoyed researching this and I spend a lot of time curating my answers. If you think I'm leaving something out, please let me know in a comment.
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')
Appeal to Authority
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 returnsFalseor 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:
NoneandFalse.
- 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 returnFalseorTrue. 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
PyObjectthat adds theob_sizefield. 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_HEADmacro.
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
I have enjoyed researching this and I spend a lot of time curating my answers. If you think I'm leaving something out, please let me know in a comment.
edited Feb 1 '18 at 15:45
answered Aug 20 '17 at 3:50
Aaron Hall♦Aaron Hall
175k51305253
175k51305253
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
4
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
add a comment |
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
4
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
This is IMO quite a good read and a valuable contribution (responding nine years after the question has been posed may have some smell, but not in this case at least for me). Thanks Aaron.
– Dilettant
May 29 '18 at 13:15
4
4
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
@Dilettant Smells are rules of thumb or heuristics that make us look closer. Some new users post late answers that essentially copy other answers, and that's the sort of thing we're concerned about when it comes to late answers. Late answers that add value are quite welcome, however - otherwise we'd close posts after some period of time, like Reddit does.
– Aaron Hall♦
May 29 '18 at 13:35
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 '17 at 11:55
Community♦
11
11
answered Dec 3 '14 at 2:21
abarnertabarnert
254k21360462
254k21360462
add a comment |
add a comment |
I have seen the below as preferred:
if not a:
print("The list is empty or null")
3
Noneis not a list; it is its own type.
– Yann Vernier
Jan 31 '18 at 9:25
add a comment |
I have seen the below as preferred:
if not a:
print("The list is empty or null")
3
Noneis not a list; it is its own type.
– Yann Vernier
Jan 31 '18 at 9:25
add a comment |
I have seen the below as preferred:
if not a:
print("The list is empty or null")
I have seen the below as preferred:
if not a:
print("The list is empty or null")
edited Feb 17 '18 at 10:34
jamylak
83.8k18177198
83.8k18177198
answered Sep 10 '08 at 6:28
hazzenhazzen
12.2k53533
12.2k53533
3
Noneis not a list; it is its own type.
– Yann Vernier
Jan 31 '18 at 9:25
add a comment |
3
Noneis not a list; it is its own type.
– Yann Vernier
Jan 31 '18 at 9:25
3
3
None is not a list; it is its own type.– Yann Vernier
Jan 31 '18 at 9:25
None is not a list; it is its own type.– Yann Vernier
Jan 31 '18 at 9:25
add a comment |
Why check at all?
No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.
I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
a =
for item in a:
<do something with item>
<rest of code>
This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient.
1
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside<rest of code>that might use the result from theforloop? 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
Feb 2 '18 at 14:02
1
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
@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
May 22 '18 at 22:45
add a comment |
Why check at all?
No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.
I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
a =
for item in a:
<do something with item>
<rest of code>
This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient.
1
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside<rest of code>that might use the result from theforloop? 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
Feb 2 '18 at 14:02
1
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
@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
May 22 '18 at 22:45
add a comment |
Why check at all?
No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.
I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
a =
for item in a:
<do something with item>
<rest of code>
This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient.
Why check at all?
No one seems to have addressed questioning your need to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.
I would argue that the most pythonic way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
a =
for item in a:
<do something with item>
<rest of code>
This has the benefit of handling any contents of a, while not requiring a specific check for emptiness. If a is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient.
edited Dec 7 '17 at 18:50
answered Oct 6 '15 at 19:25
MrWonderfulMrWonderful
1,7731218
1,7731218
1
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside<rest of code>that might use the result from theforloop? 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
Feb 2 '18 at 14:02
1
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
@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
May 22 '18 at 22:45
add a comment |
1
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside<rest of code>that might use the result from theforloop? 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
Feb 2 '18 at 14:02
1
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
@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
May 22 '18 at 22:45
1
1
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside
<rest of code> that might use the result from the for loop? Or directly use some values in a? Indeed, if the script is designed to run with strictly controlled input, the check might be a little unnecessary. But in most cases, the input varies, and have a check is usually better.– Amarth Gûl
Feb 2 '18 at 14:02
The thing is, check if the list is empty is quite important, at least for me. Have you considered if there's some script inside
<rest of code> that might use the result from the for loop? Or directly use some values in a? Indeed, if the script is designed to run with strictly controlled input, the check might be a little unnecessary. But in most cases, the input varies, and have a check is usually better.– Amarth Gûl
Feb 2 '18 at 14:02
1
1
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
This is a good point in most cases
– jamylak
Feb 17 '18 at 10:35
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
Respectfully, no. What I considered was someone who didn’t know enough about Python to know that “if <list>:” was the correct answer, asked how to check for an empty list. Then I notice a LOT of answers that offered differing opinions, but none seemed to address the original need. That is what I tried to do with my answer—have them examine the need before continuing. I believe I suggested as much in my answer, explicitly.
– MrWonderful
Feb 17 '18 at 19:18
@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
May 22 '18 at 22:45
@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
May 22 '18 at 22:45
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Jun 14 '12 at 1:03
Ry-♦
169k40342359
169k40342359
answered Sep 15 '08 at 5:50
George V. ReillyGeorge V. Reilly
11.1k53237
11.1k53237
add a comment |
add a comment |
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.
2
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, likecollections.abc.Sizedorcollections.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
Dec 3 '14 at 2:09
11
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 exactlyand not something falsy of another type, then surelyif 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 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
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 4:47
add a comment |
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.
2
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, likecollections.abc.Sizedorcollections.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
Dec 3 '14 at 2:09
11
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 exactlyand not something falsy of another type, then surelyif 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 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
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 4:47
add a comment |
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.
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.
edited Jun 25 '15 at 3:10
Mike
9,73663867
9,73663867
answered May 31 '12 at 14:35
dubiousjimdubiousjim
3,88712728
3,88712728
2
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, likecollections.abc.Sizedorcollections.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
Dec 3 '14 at 2:09
11
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 exactlyand not something falsy of another type, then surelyif 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 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
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 4:47
add a comment |
2
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, likecollections.abc.Sizedorcollections.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
Dec 3 '14 at 2:09
11
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 exactlyand not something falsy of another type, then surelyif 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 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
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 4:47
2
2
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 3 '14 at 2:09
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 3 '14 at 2:09
11
11
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
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
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
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
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
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 4:47
@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 4:47
add a comment |
Python is very uniform about the treatment of emptiness. Given the following:
a =
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
add a comment |
Python is very uniform about the treatment of emptiness. Given the following:
a =
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
add a comment |
Python is very uniform about the treatment of emptiness. Given the following:
a =
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
Python is very uniform about the treatment of emptiness. Given the following:
a =
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.
answered Jun 2 '12 at 15:40
octopusgrabbusoctopusgrabbus
6,5821043101
6,5821043101
add a comment |
add a comment |
From documentation on truth value testing:
All values other than what is listed here are considered True
NoneFalse- 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!')
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
@DJ_Stuffy_K assert what in unit testing, an empty list? Just useassert(not myList). If you also want to assert the object is alist, you can useassertIsInstance().
– Sнаđошƒаӽ
Sep 1 '18 at 5:39
add a comment |
From documentation on truth value testing:
All values other than what is listed here are considered True
NoneFalse- 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!')
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
@DJ_Stuffy_K assert what in unit testing, an empty list? Just useassert(not myList). If you also want to assert the object is alist, you can useassertIsInstance().
– Sнаđошƒаӽ
Sep 1 '18 at 5:39
add a comment |
From documentation on truth value testing:
All values other than what is listed here are considered True
NoneFalse- 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!')
From documentation on truth value testing:
All values other than what is listed here are considered True
NoneFalse- 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!')
edited Jan 11 '16 at 17:40
answered Jan 1 '16 at 18:18
SнаđошƒаӽSнаđошƒаӽ
7,284104365
7,284104365
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
@DJ_Stuffy_K assert what in unit testing, an empty list? Just useassert(not myList). If you also want to assert the object is alist, you can useassertIsInstance().
– Sнаđошƒаӽ
Sep 1 '18 at 5:39
add a comment |
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
@DJ_Stuffy_K assert what in unit testing, an empty list? Just useassert(not myList). If you also want to assert the object is alist, you can useassertIsInstance().
– Sнаđошƒаӽ
Sep 1 '18 at 5:39
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
how do we assert this when using unite testing?
– DJ_Stuffy_K
Mar 21 '18 at 18:21
@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().– Sнаđошƒаӽ
Sep 1 '18 at 5:39
@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().– Sнаđошƒаӽ
Sep 1 '18 at 5:39
add a comment |
Some methods that I use:
if not a:
print "list is empty"
if len(a) == 0:
print "list is empty"
add a comment |
Some methods that I use:
if not a:
print "list is empty"
if len(a) == 0:
print "list is empty"
add a comment |
Some methods that I use:
if not a:
print "list is empty"
if len(a) == 0:
print "list is empty"
Some methods that I use:
if not a:
print "list is empty"
if len(a) == 0:
print "list is empty"
edited Mar 27 '18 at 11:31
answered Oct 27 '14 at 0:35
HackaholicHackaholic
12.4k12540
12.4k12540
add a comment |
add a comment |
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")
add a comment |
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")
add a comment |
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")
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")
answered Nov 28 '16 at 14:18
InconnuInconnu
3,65322033
3,65322033
add a comment |
add a comment |
I prefer the following:
if a == :
print "The list is empty."
26
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
22
this is less readable thanif not a:and breaks more easily. Please don't do it.
– devsnd
Nov 12 '12 at 11:23
add a comment |
I prefer the following:
if a == :
print "The list is empty."
26
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
22
this is less readable thanif not a:and breaks more easily. Please don't do it.
– devsnd
Nov 12 '12 at 11:23
add a comment |
I prefer the following:
if a == :
print "The list is empty."
I prefer the following:
if a == :
print "The list is empty."
edited Jan 5 at 4:25
Boris
1,31511427
1,31511427
answered Sep 10 '08 at 6:43
verixverix
8232811
8232811
26
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
22
this is less readable thanif not a:and breaks more easily. Please don't do it.
– devsnd
Nov 12 '12 at 11:23
add a comment |
26
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
22
this is less readable thanif not a:and breaks more easily. Please don't do it.
– devsnd
Nov 12 '12 at 11:23
26
26
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
This is going to be slower, as you instantiate an extra empty list unnecessarily.
– Carl Meyer
Sep 10 '08 at 13:42
22
22
this is less readable than
if not a: and breaks more easily. Please don't do it.– devsnd
Nov 12 '12 at 11:23
this is less readable than
if not a: and breaks more easily. Please don't do it.– devsnd
Nov 12 '12 at 11:23
add a comment |
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
add a comment |
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
add a comment |
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
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
edited May 26 '16 at 14:10
ppperry
2,85111428
2,85111428
answered Apr 13 '16 at 21:55
TagarTagar
4,96934266
4,96934266
add a comment |
add a comment |
Another simple way could be
a =
if len(a) == 0:
print("Empty")
else:
print(" Not empty")
add a comment |
Another simple way could be
a =
if len(a) == 0:
print("Empty")
else:
print(" Not empty")
add a comment |
Another simple way could be
a =
if len(a) == 0:
print("Empty")
else:
print(" Not empty")
Another simple way could be
a =
if len(a) == 0:
print("Empty")
else:
print(" Not empty")
answered Mar 19 '18 at 11:14
Devendra BhatDevendra Bhat
5071714
5071714
add a comment |
add a comment |
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
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
add a comment |
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
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
add a comment |
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
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
edited Nov 6 '18 at 10:12
answered Nov 6 '18 at 9:55
Dheeraj M PaiDheeraj M Pai
16712
16712
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
add a comment |
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
please give more explanation about how it is working without writing "if"?
– ganeshdeshmukh
Dec 30 '18 at 10:48
add a comment |
You can check if the length of the array is zero (or not.) If the length of the array is zero, then it is empty. try the following:
a =
if len(a)==0 : print "List is empty"
Using%timeitin ipdb,len(a)is almost 50% faster thanbool(a), however pep 8 would recommend usingbool(a).
– raratiru
Dec 21 '18 at 18:42
add a comment |
You can check if the length of the array is zero (or not.) If the length of the array is zero, then it is empty. try the following:
a =
if len(a)==0 : print "List is empty"
Using%timeitin ipdb,len(a)is almost 50% faster thanbool(a), however pep 8 would recommend usingbool(a).
– raratiru
Dec 21 '18 at 18:42
add a comment |
You can check if the length of the array is zero (or not.) If the length of the array is zero, then it is empty. try the following:
a =
if len(a)==0 : print "List is empty"
You can check if the length of the array is zero (or not.) If the length of the array is zero, then it is empty. try the following:
a =
if len(a)==0 : print "List is empty"
answered Nov 14 '18 at 19:02
Siddharth SatpathySiddharth Satpathy
5441516
5441516
Using%timeitin ipdb,len(a)is almost 50% faster thanbool(a), however pep 8 would recommend usingbool(a).
– raratiru
Dec 21 '18 at 18:42
add a comment |
Using%timeitin ipdb,len(a)is almost 50% faster thanbool(a), however pep 8 would recommend usingbool(a).
– raratiru
Dec 21 '18 at 18:42
Using
%timeit in ipdb, len(a) is almost 50% faster than bool(a), however pep 8 would recommend using bool(a).– raratiru
Dec 21 '18 at 18:42
Using
%timeit in ipdb, len(a) is almost 50% faster than bool(a), however pep 8 would recommend using bool(a).– raratiru
Dec 21 '18 at 18:42
add a comment |
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
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
1
If I wasn't happy withif a:, it would be because I wanted an exception ifawasn'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 2:40
add a comment |
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
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
1
If I wasn't happy withif a:, it would be because I wanted an exception ifawasn'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 2:40
add a comment |
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
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
answered Mar 29 '17 at 2:58
AndreyS ScherbakovAndreyS Scherbakov
2,00211219
2,00211219
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
1
If I wasn't happy withif a:, it would be because I wanted an exception ifawasn'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 2:40
add a comment |
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
1
If I wasn't happy withif a:, it would be because I wanted an exception ifawasn'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 2:40
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
Overbroad; this is just asking whether a list is empty, not whether something is an empty iterable.
– ppperry
Jul 12 '17 at 15:47
1
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 2:40
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 2:40
add a comment |
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, ifais not a list andahas no method__len__implemented. I would recommend:if isinstance(obj, list): if len(obj) == 0: print '...'
– Sven Krüger
Jan 10 at 9:40
add a comment |
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, ifais not a list andahas no method__len__implemented. I would recommend:if isinstance(obj, list): if len(obj) == 0: print '...'
– Sven Krüger
Jan 10 at 9:40
add a comment |
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")
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")
answered Oct 12 '18 at 4:01
HackerBossHackerBoss
682411
682411
It is possible this throws an exception, ifais not a list andahas no method__len__implemented. I would recommend:if isinstance(obj, list): if len(obj) == 0: print '...'
– Sven Krüger
Jan 10 at 9:40
add a comment |
It is possible this throws an exception, ifais not a list andahas no method__len__implemented. I would recommend:if isinstance(obj, list): if len(obj) == 0: print '...'
– Sven Krüger
Jan 10 at 9:40
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 Krüger
Jan 10 at 9:40
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 Krüger
Jan 10 at 9:40
add a comment |
we could use a simple if else:
list=
if len(list)==0:
print ("list is empty")
else:
print ("list is not empty")
add a comment |
we could use a simple if else:
list=
if len(list)==0:
print ("list is empty")
else:
print ("list is not empty")
add a comment |
we could use a simple if else:
list=
if len(list)==0:
print ("list is empty")
else:
print ("list is not empty")
we could use a simple if else:
list=
if len(list)==0:
print ("list is empty")
else:
print ("list is not empty")
answered Jan 6 at 19:15
l. zhangl. zhang
473
473
add a comment |
add a comment |
You can even try using bool() like this
a = [1,2,3];
print bool(a); # it will return True
a = ;
print bool(a); # it will return False
I love this way for checking list is empty or not.
Very handy and useful.
4
For those (like me) who didn't know,bool()converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.
– 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
add a comment |
You can even try using bool() like this
a = [1,2,3];
print bool(a); # it will return True
a = ;
print bool(a); # it will return False
I love this way for checking list is empty or not.
Very handy and useful.
4
For those (like me) who didn't know,bool()converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.
– 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
add a comment |
You can even try using bool() like this
a = [1,2,3];
print bool(a); # it will return True
a = ;
print bool(a); # it will return False
I love this way for checking list is empty or not.
Very handy and useful.
You can even try using bool() like this
a = [1,2,3];
print bool(a); # it will return True
a = ;
print bool(a); # it will return False
I love this way for checking list is empty or not.
Very handy and useful.
answered Sep 13 '16 at 11:53
Sunil LullaSunil Lulla
410310
410310
4
For those (like me) who didn't know,bool()converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.
– 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
add a comment |
4
For those (like me) who didn't know,bool()converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.
– 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
4
4
For those (like me) who didn't know,
bool() converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.– Galen Long
Mar 10 '17 at 21:42
For those (like me) who didn't know,
bool() converts a Python variable into a boolean so you can store the truthiness or falsiness of a value without having to use an if-statement. I think it's less readable than simply using a conditional like the accepted answer, but I'm sure there are other good use cases for it.– 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
This is usable in an expression and is more terse.
– qneill
Dec 18 '17 at 21:13
add a comment |
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
add a comment |
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
add a comment |
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
Simple way is checking the length is equal zero.
if len(a) == 0:
print("a is empty")
answered Oct 12 '18 at 2:59
Ashiq ImranAshiq Imran
13214
13214
add a comment |
add a comment |
print('not empty' if a else 'empty')
a little more practical:
a.pop() if a else None
add a comment |
print('not empty' if a else 'empty')
a little more practical:
a.pop() if a else None
add a comment |
print('not empty' if a else 'empty')
a little more practical:
a.pop() if a else None
print('not empty' if a else 'empty')
a little more practical:
a.pop() if a else None
edited Nov 3 '18 at 2:41
answered Nov 3 '18 at 2:23
Andrey SuglobovAndrey Suglobov
1349
1349
add a comment |
add a comment |
Check if: len(list) == 0 returns: True
I see that pylint complains about this:>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214it is way slower
– MortenB
Feb 8 at 10:18
add a comment |
Check if: len(list) == 0 returns: True
I see that pylint complains about this:>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214it is way slower
– MortenB
Feb 8 at 10:18
add a comment |
Check if: len(list) == 0 returns: True
Check if: len(list) == 0 returns: True
answered Jan 31 at 10:41
LeevoLeevo
1767
1767
I see that pylint complains about this:>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214it is way slower
– MortenB
Feb 8 at 10:18
add a comment |
I see that pylint complains about this:>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214it is way slower
– MortenB
Feb 8 at 10:18
I see that pylint complains about this:
>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214 it is way slower– MortenB
Feb 8 at 10:18
I see that pylint complains about this:
>>> timeit.timeit(setup='None', stmt="list=; bool(list)", number=10000) 0.0009641999999985273 >>> timeit.timeit(setup='None', stmt="list=; bool(len(list))", number=10000) 0.002756199999993214 it is way slower– MortenB
Feb 8 at 10:18
add a comment |
Method 1 (Preferred):
if not a :
print ("Empty")
Method 2 :
if len(a) == 0 :
print( "Empty" )
Method 3:
if a == :
print ("Empty")
add a comment |
Method 1 (Preferred):
if not a :
print ("Empty")
Method 2 :
if len(a) == 0 :
print( "Empty" )
Method 3:
if a == :
print ("Empty")
add a comment |
Method 1 (Preferred):
if not a :
print ("Empty")
Method 2 :
if len(a) == 0 :
print( "Empty" )
Method 3:
if a == :
print ("Empty")
Method 1 (Preferred):
if not a :
print ("Empty")
Method 2 :
if len(a) == 0 :
print( "Empty" )
Method 3:
if a == :
print ("Empty")
answered Feb 9 at 23:59
VikrantVikrant
178112
178112
add a comment |
add a comment |
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).
3
The nameis_emptysuggests that it returns something. But if it did, that something would just bebool(any_structure), which you should use instead (when you need aboolat all).
– Davis Herring
Sep 20 '17 at 2:39
2
Why do we want a variation onboolthat (also) prints messages to standard output?
– Davis Herring
Sep 20 '17 at 3:13
@DavisHerring We always have two choice first is to print using function other is using returnboolvariable. Choice is yours. I write both so you can choose between them.
– Vineet Jain
Sep 20 '17 at 3:45
add a comment |
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).
3
The nameis_emptysuggests that it returns something. But if it did, that something would just bebool(any_structure), which you should use instead (when you need aboolat all).
– Davis Herring
Sep 20 '17 at 2:39
2
Why do we want a variation onboolthat (also) prints messages to standard output?
– Davis Herring
Sep 20 '17 at 3:13
@DavisHerring We always have two choice first is to print using function other is using returnboolvariable. Choice is yours. I write both so you can choose between them.
– Vineet Jain
Sep 20 '17 at 3:45
add a comment |
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).
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).
edited Sep 20 '17 at 2:59
answered Aug 26 '17 at 19:04
Vineet JainVineet Jain
92841129
92841129
3
The nameis_emptysuggests that it returns something. But if it did, that something would just bebool(any_structure), which you should use instead (when you need aboolat all).
– Davis Herring
Sep 20 '17 at 2:39
2
Why do we want a variation onboolthat (also) prints messages to standard output?
– Davis Herring
Sep 20 '17 at 3:13
@DavisHerring We always have two choice first is to print using function other is using returnboolvariable. Choice is yours. I write both so you can choose between them.
– Vineet Jain
Sep 20 '17 at 3:45
add a comment |
3
The nameis_emptysuggests that it returns something. But if it did, that something would just bebool(any_structure), which you should use instead (when you need aboolat all).
– Davis Herring
Sep 20 '17 at 2:39
2
Why do we want a variation onboolthat (also) prints messages to standard output?
– Davis Herring
Sep 20 '17 at 3:13
@DavisHerring We always have two choice first is to print using function other is using returnboolvariable. Choice is yours. I write both so you can choose between them.
– Vineet Jain
Sep 20 '17 at 3:45
3
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 2:39
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 2:39
2
2
Why do we want a variation on
bool that (also) prints messages to standard output?– Davis Herring
Sep 20 '17 at 3:13
Why do we want a variation on
bool that (also) prints messages to standard output?– Davis Herring
Sep 20 '17 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
Sep 20 '17 at 3:45
@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 3:45
add a comment |
If you want to check if list is empty;
l =
if l:
# do your stuff.
If you want to check weather all the values in list is empty.
l = ["", False, 0, '', , {}, ()]
if all(bool(x) for x in l):
# do your stuff.
However this will be True for empty list.
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.
1
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
add a comment |
If you want to check if list is empty;
l =
if l:
# do your stuff.
If you want to check weather all the values in list is empty.
l = ["", False, 0, '', , {}, ()]
if all(bool(x) for x in l):
# do your stuff.
However this will be True for empty list.
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.
1
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
add a comment |
If you want to check if list is empty;
l =
if l:
# do your stuff.
If you want to check weather all the values in list is empty.
l = ["", False, 0, '', , {}, ()]
if all(bool(x) for x in l):
# do your stuff.
However this will be True for empty list.
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.
If you want to check if list is empty;
l =
if l:
# do your stuff.
If you want to check weather all the values in list is empty.
l = ["", False, 0, '', , {}, ()]
if all(bool(x) for x in l):
# do your stuff.
However this will be True for empty list.
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.
edited Mar 5 '18 at 17:32
answered Mar 5 '18 at 11:30
RahulRahul
4,83532153
4,83532153
1
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
add a comment |
1
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
1
1
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
all(bool(x) for x in l) is True for an empty list
– gberger
Mar 5 '18 at 17:27
add a comment |
1 2
next
protected by Srikar Appalaraju Feb 22 '13 at 8:10
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?