How do I check if a list is empty?

2018-12-31 04:46发布

For example, if passed the following:

a = []

How do I check to see if a is empty?

标签: python list
30条回答
柔情千种
2楼-- · 2018-12-31 05:03

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.

查看更多
不再属于我。
3楼-- · 2018-12-31 05:04

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.

查看更多
冷夜・残月
4楼-- · 2018-12-31 05:06

From documentation on truth value testing:

All values other than what is listed here are considered True

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

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

if not a:
    print('"a" is empty!')
查看更多
梦该遗忘
5楼-- · 2018-12-31 05:06

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")
查看更多
与君花间醉酒
6楼-- · 2018-12-31 05:07

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 returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

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

And the datamodel documentation:

object.__bool__(self)

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

and

object.__len__(self)

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

So instead of this:

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

or this:

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

Do this:

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

Doing what's Pythonic usually pays off in performance:

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

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

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

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

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

Why?

For the len(a) == 0 check:

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

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

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

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

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

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

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

Evidence from the C source and documentation

PyVarObject

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

From the c source in Include/listobject.h:

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

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

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.

查看更多
皆成旧梦
7楼-- · 2018-12-31 05:08

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.

查看更多
登录 后发表回答