如何检查列表是否为空?

时间:2021-07-19 01:58:17

For example, if passed the following:

例如,如果通过以下步骤:

a = []

How do I check to see if a is empty?

如何检查a是否为空?

26 个解决方案

#1


3808  

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

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

使用空列表的隐式booleanness是非常python化的。

#2


845  

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

python化的方法来自PEP 8风格指南(其中Yes表示“推荐”,No表示“不推荐”):

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

对于序列(字符串、列表、元组),使用空序列为false的事实。

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):

#3


501  

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.

这样就可以100%地确定li是一个序列(list),我们想要测试它的大小。如果不是李,我的问题是:……它给人的错误印象是li是一个布尔变量。

#4


198  

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

其他一些人似乎在概括这个问题,而不仅仅是列表,所以我认为我应该为许多人可能使用的不同类型的序列添加一个警告,特别是因为这是“python测试空数组”的第一个谷歌命中。

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.

您需要小心使用numpy数组,因为其他用于列表或其他标准容器的方法对于numpy数组来说是失败的。下面我将解释为什么,但简而言之,首选的方法是使用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:

“python化”的方法在numpy数组中失败,因为numpy试图将数组转换为一个bools数组,如果x试图一次性计算所有这些bools以获得某种聚合的真值。但是这没有任何意义,所以你会得到一个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:

但至少上面的例子告诉你它失败了。如果您恰好有一个只有一个元素的numpy数组,那么If语句就会“工作”,因为您不会得到错误。但是,如果一个元素恰好是0(或0.0,或false,…),则if语句将不正确地导致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.

但显然x存在,而且不是空的!这个结果不是你想要的。

Using len can give unexpected results

For example,

例如,

len( numpy.zeros((1,0)) )

returns 1, even though the array has zero elements.

返回1,即使数组中没有元素。

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:

正如在scipy FAQ中所解释的,在所有您知道有numpy数组的情况下,正确的方法是使用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.

如果您不确定它是列表、numpy数组还是其他什么,可以将这种方法与@dubiousjim给出的答案结合,以确保每种类型都使用了正确的测试。虽然不是很“毕达哥拉斯式”,但numpy至少在这个意义上故意打破了毕达哥拉斯式。

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:

如果您需要做的不仅仅是检查输入是否为空,并且您正在使用其他numpy特性(如索引或数学操作),那么将输入强制为numpy数组可能更有效(当然也更常见)。有一些很好的函数可以快速完成这个任务——最重要的是numpi .asarray。它接受您的输入,如果它已经是一个数组,它什么都不做,或者如果它是一个列表、tuple等,它将您的输入包装到一个数组中,并且可以选择将它转换为您所选择的dtype。所以无论何时它都是非常快的,它确保你只要假设输入是一个numpy数组。我们甚至通常只使用相同的名称,因为对数组的转换不会使它回到当前范围之外:

x = numpy.asarray(x, dtype=numpy.double)

This will make the x.size check work in all cases I see on this page.

这就是x。尺寸检查在所有情况下,我看到在这一页。

#5


99  

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

在真值测试中,空列表本身被认为是假的(请参阅python文档):

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

@Daren Thomas

@Daren托马斯

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?

编辑:另一点反对将空列表测试为False:那么多态性呢?你不应该把清单当成清单。它应该像鸭子一样嘎嘎叫——当它没有元素的时候,你怎么能让你的鸭子系列嘎嘎叫“假”呢?

Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.

您的duckCollection应该实现__nonzero__或__len__,所以if a:将毫无问题地工作。

#6


80  

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.

帕特里克(被接受的)回答是对的:如果不是a:是正确的方法。Harley Holcombe的答案是对的,这是在PEP 8风格指南中。但是没有一个答案能解释为什么遵循这个习惯是一个好主意——即使你个人觉得它不够明确,或者对Ruby用户或其他什么不清楚。

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.

Python代码和Python社区具有非常强的习惯用法。遵循这些习惯用法可以使您的代码更容易阅读,对于任何有Python经验的人来说都是如此。当你违反这些习语时,这是一个强烈的信号。

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.

如果不是a:就不能区分空列表和空列表、数字0、空元组、空用户创建的集合类型、空用户创建的非基本集合类型、单元素NumPy数组和falsey值等。在这种情况下,你知道你想要明确什么,所以你可以测试它。例如,如果不是a和a不是None:表示“除了None之外的任何东西”,而如果len(a) != 0:表示“只有空的序列——除了序列之外的任何东西都是一个错误”,等等。除了测试您想要测试的内容之外,这也向读者表明这个测试是重要的。

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.

但是当你没有任何东西需要明确说明的时候,除了a之外的任何东西都会误导读者。你是在发出重要的信号,而实际上并不重要。(你也可能使代码变得不那么灵活,或者更慢,或者别的什么,但这些都不那么重要。)如果你习惯性地误导读者,那么当你需要区分的时候,它就会被忽略,因为你一直在你的代码中“哭喊着狼来了”。

#7


71  

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?

如何检查a是否为空?

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或while语句)。如果它是空的,它将测试False,否则它将测试True。例如:

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:

Python标准库中Python代码的官方Python风格指南,断言:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

对于序列(字符串、列表、元组),使用空序列为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.

它们在各自的其他语言中是正确的。在Python中这在语义上是正确的。

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

但是我们认为它是非Python的,因为Python通过布尔强制方法直接在列表对象的接口中支持这些语义。

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:

默认情况下,对象被认为是true,除非它的类定义了__bool__()方法,该方法返回False,或者__len__()方法,该方法在对象被调用时返回0。以下是大多数被认为是假的内置对象:

  • constants defined to be false: None and False.
  • 定义为false的常量:None和false。
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • 0、0、0、0j、小数(0)、分数(0、1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)
  • 空序列和集合:“,(),[],{},set(), range(0)

And the datamodel documentation:

和datamodel文档:

object.__bool__(self)

object.__bool__(自我)

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.

调用实现真值测试和内置操作bool();应该返回False或True。当没有定义该方法时,如果定义了__len__(),则调用__len__();如果定义了该方法,则如果结果为非零,则认为该对象为真。如果一个类既没有定义__len__()也没有定义__bool__(),那么它的所有实例都被认为是正确的。

and

object.__len__(self)

object.__len__(自我)

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.

调用来实现内置函数len()。应该返回对象的长度,一个整数>= 0。另外,在布尔上下文中,不定义__bool__()方法且其__len__()方法返回零的对象被认为是假的。

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.

我们可以看到,使用内建函数len与0进行长度检查,或者使用空列表进行检查,都比使用有文档说明的语言内建语法要低得多。

Why?

为什么?

For the len(a) == 0 check:

对于len(a) = 0检查:

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

首先Python必须检查全局,看看len是否被跟踪。

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

然后它必须调用函数,load 0,并在Python中进行相等比较(而不是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)

对于[]=[],它必须构建一个不必要的列表,然后在Python的虚拟机(与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:

“python”方法是一种更简单、更快速的检查方法,因为列表的长度被缓存在对象实例头中:

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

Evidence from the C source and documentation

PyVarObject

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.

这是PyObject的扩展,它添加了ob_size字段。这只用于具有长度概念的对象。这种类型通常不会出现在Python/C API中。它对应于PyObject_VAR_HEAD宏展开所定义的字段。

From the c source in Include/listobject.h:

从包含/列表项中的c来源:

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.

我很喜欢研究这个问题,我花了很多时间整理我的答案。如果你认为我遗漏了什么,请在评论中告诉我。

#8


61  

I have seen the below as preferred:

我认为以下是我的首选:

if not a:
    print("The list is empty or null")

#9


48  

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.

似乎没有人会在一开始就质疑你是否需要测试这份清单。由于您没有提供额外的上下文,我可以想象您可能首先不需要做这个检查,但是不熟悉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.

这可以处理a的任何内容,而不需要对空性进行特定的检查。如果a是空的,则依赖块将不会执行,解释器将会掉到下一行。

If you do actually need to check the array for emptiness, the other answers are sufficient.

如果你确实需要检查空的数组,其他的答案就足够了。

#10


44  

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.

len()是Python列表、字符串、dicts和set的O(1)操作。Python在内部跟踪这些容器中的元素数量。

JavaScript has a similar notion of truthy/falsy.

JavaScript也有类似的truthy/falsy的概念。

#11


27  

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:

被选为1。我不确定这是不是因为读者反对这一策略,或者认为答案毫无帮助。我将假设它是后者,因为-- --不管什么叫“毕达哥拉斯式”---这是正确的策略。除非您已经排除了,或者准备处理a为False的情况,否则您需要进行比a为非a的更严格的测试。你可以用这样的东西:

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:

第一个测试是对上面@Mike的回答的回应。第三行也可以改为:

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.

你可以没有显式类型检查,如果周围的环境已经向你保证是一个值类型的你准备处理,或者如果你确定类型不准备处理会提高错误(例如,TypeError如果你叫len值的定义),你准备处理。一般来说,“python”的约定似乎是这样的。像鸭子一样挤它,如果它不知道如何嘎嘎叫,就让它发出鸭子的叫声。你仍然需要考虑你所做的类型假设,以及你没有准备好处理的情况是否真的会在正确的地方出错。Numpy数组是一个很好的例子,它只是盲目地依赖len或布尔型类型,可能无法精确地完成您所期望的工作。

#12


24  

Python is very uniform about the treatment of emptiness. Given the following:

对于空的处理,Python是非常统一的。鉴于以下几点:

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.

您只需用“if”语句检查列表a,看看它是否为空。从我所读到的和学到的内容来看,这是一种“python化”的方式,可以查看列表或元组是否为空。

#13


18  

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.
  • 任何数字类型的零,例如,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.
  • 用户定义类的实例,如果类定义了__bool__()或__len__()方法,当该方法返回整数值0或bool值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!')

#14


15  

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

以下是一些检查列表是否为空的方法:

a = [] #the list

1) The pretty simple pythonic way:

1)简单的毕达哥拉斯式:

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.

在Python中,诸如列表、元组、集合、命令、变量等空容器被视为假的。可以简单地将列表视为谓词(返回布尔值)。一个真值表示它是非空的。

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

2)一种非常明确的方法:使用len()查找长度并检查它是否等于0:

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

3) Or comparing it to an anonymous empty list:

3)或将其与匿名空列表进行比较:

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

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

4)另一种愚蠢的方法是使用exception和iter():

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

#15


13  

Some methods that I use:

我使用的一些方法:

if not a:
    print "list is empty"


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

#16


5  

I prefer the following:

我更喜欢下面的:

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

Readable and you don't have to worry about calling a function like len() to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unless a was gigantic.

可读,您不必担心调用像len()这样的函数来迭代变量。虽然我不太确定这种东西的BigO符号是什么。但是Python的速度如此之快,我怀疑它是否重要,除非a是巨大的。

#17


5  

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

#18


2  

Another simple way could be

另一个简单的方法是

a = []
if len(a) == 0:
  print("Empty")
else:
  print(" Not empty")

#19


1  

You can even try using bool() like this

您甚至可以尝试像这样使用bool()

    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.

非常方便和有用的。

#20


1  

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.

#21


0  

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

受到@dubiousjim的解决方案的启发,我建议使用一个额外的通用检查,看看它是否是可迭代的

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

注意:字符串被认为是可迭代的。-如果要排除空字符串,则添加而不是isinstance(a,(str,unicode))

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

#22


0  

Simply use is_empty() or make function like:-

只需使用is_empty()或使函数如:-

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

它可以用于任何data_structure,如列表、元组、字典等。通过这些,您可以使用is_empty(any_structure)多次调用它。

#23


-1  

An unofficial approach :

一个非官方的方式:

 a = []
 try:
  print(a[-1])
 except IndexError:
  print("List is empty")

#24


-1  

Look at the following code executed on Python interactive terminal.

查看在Python交互式终端上执行的以下代码。

>>> a = []
>>> if a:
...     print "List is not empty";
... else:
...     print "List is empty"
... 
List is empty
>>> 
>>> a = [1, 4, 9]
>>> if a:
...     print "List is not empty";
... else:
...     print "List is empty"
... 
List is not empty
>>> 

#25


-1  

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

空列表的真值为False,而非空列表的真值为True。

#26


-3  

i think people suggested for

我认为人们建议

if len(list1) == 0:
    print("is a good way")

or len you can count by

或者你可以用len (count by)

if list1.__ len__()==0:
    print("list1 is empty")

you can use one more way

你可以再用一种方法

if list1.__ sizeof__() == 40:
    print("list1 is empty")

size of empty list is always 40.

空列表的大小总是40。

#1


3808  

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

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

使用空列表的隐式booleanness是非常python化的。

#2


845  

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

python化的方法来自PEP 8风格指南(其中Yes表示“推荐”,No表示“不推荐”):

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

对于序列(字符串、列表、元组),使用空序列为false的事实。

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):

#3


501  

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.

这样就可以100%地确定li是一个序列(list),我们想要测试它的大小。如果不是李,我的问题是:……它给人的错误印象是li是一个布尔变量。

#4


198  

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

其他一些人似乎在概括这个问题,而不仅仅是列表,所以我认为我应该为许多人可能使用的不同类型的序列添加一个警告,特别是因为这是“python测试空数组”的第一个谷歌命中。

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.

您需要小心使用numpy数组,因为其他用于列表或其他标准容器的方法对于numpy数组来说是失败的。下面我将解释为什么,但简而言之,首选的方法是使用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:

“python化”的方法在numpy数组中失败,因为numpy试图将数组转换为一个bools数组,如果x试图一次性计算所有这些bools以获得某种聚合的真值。但是这没有任何意义,所以你会得到一个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:

但至少上面的例子告诉你它失败了。如果您恰好有一个只有一个元素的numpy数组,那么If语句就会“工作”,因为您不会得到错误。但是,如果一个元素恰好是0(或0.0,或false,…),则if语句将不正确地导致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.

但显然x存在,而且不是空的!这个结果不是你想要的。

Using len can give unexpected results

For example,

例如,

len( numpy.zeros((1,0)) )

returns 1, even though the array has zero elements.

返回1,即使数组中没有元素。

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:

正如在scipy FAQ中所解释的,在所有您知道有numpy数组的情况下,正确的方法是使用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.

如果您不确定它是列表、numpy数组还是其他什么,可以将这种方法与@dubiousjim给出的答案结合,以确保每种类型都使用了正确的测试。虽然不是很“毕达哥拉斯式”,但numpy至少在这个意义上故意打破了毕达哥拉斯式。

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:

如果您需要做的不仅仅是检查输入是否为空,并且您正在使用其他numpy特性(如索引或数学操作),那么将输入强制为numpy数组可能更有效(当然也更常见)。有一些很好的函数可以快速完成这个任务——最重要的是numpi .asarray。它接受您的输入,如果它已经是一个数组,它什么都不做,或者如果它是一个列表、tuple等,它将您的输入包装到一个数组中,并且可以选择将它转换为您所选择的dtype。所以无论何时它都是非常快的,它确保你只要假设输入是一个numpy数组。我们甚至通常只使用相同的名称,因为对数组的转换不会使它回到当前范围之外:

x = numpy.asarray(x, dtype=numpy.double)

This will make the x.size check work in all cases I see on this page.

这就是x。尺寸检查在所有情况下,我看到在这一页。

#5


99  

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

在真值测试中,空列表本身被认为是假的(请参阅python文档):

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

@Daren Thomas

@Daren托马斯

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?

编辑:另一点反对将空列表测试为False:那么多态性呢?你不应该把清单当成清单。它应该像鸭子一样嘎嘎叫——当它没有元素的时候,你怎么能让你的鸭子系列嘎嘎叫“假”呢?

Your duckCollection should implement __nonzero__ or __len__ so the if a: will work without problems.

您的duckCollection应该实现__nonzero__或__len__,所以if a:将毫无问题地工作。

#6


80  

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.

帕特里克(被接受的)回答是对的:如果不是a:是正确的方法。Harley Holcombe的答案是对的,这是在PEP 8风格指南中。但是没有一个答案能解释为什么遵循这个习惯是一个好主意——即使你个人觉得它不够明确,或者对Ruby用户或其他什么不清楚。

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.

Python代码和Python社区具有非常强的习惯用法。遵循这些习惯用法可以使您的代码更容易阅读,对于任何有Python经验的人来说都是如此。当你违反这些习语时,这是一个强烈的信号。

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.

如果不是a:就不能区分空列表和空列表、数字0、空元组、空用户创建的集合类型、空用户创建的非基本集合类型、单元素NumPy数组和falsey值等。在这种情况下,你知道你想要明确什么,所以你可以测试它。例如,如果不是a和a不是None:表示“除了None之外的任何东西”,而如果len(a) != 0:表示“只有空的序列——除了序列之外的任何东西都是一个错误”,等等。除了测试您想要测试的内容之外,这也向读者表明这个测试是重要的。

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.

但是当你没有任何东西需要明确说明的时候,除了a之外的任何东西都会误导读者。你是在发出重要的信号,而实际上并不重要。(你也可能使代码变得不那么灵活,或者更慢,或者别的什么,但这些都不那么重要。)如果你习惯性地误导读者,那么当你需要区分的时候,它就会被忽略,因为你一直在你的代码中“哭喊着狼来了”。

#7


71  

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?

如何检查a是否为空?

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或while语句)。如果它是空的,它将测试False,否则它将测试True。例如:

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:

Python标准库中Python代码的官方Python风格指南,断言:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

对于序列(字符串、列表、元组),使用空序列为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.

它们在各自的其他语言中是正确的。在Python中这在语义上是正确的。

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

但是我们认为它是非Python的,因为Python通过布尔强制方法直接在列表对象的接口中支持这些语义。

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:

默认情况下,对象被认为是true,除非它的类定义了__bool__()方法,该方法返回False,或者__len__()方法,该方法在对象被调用时返回0。以下是大多数被认为是假的内置对象:

  • constants defined to be false: None and False.
  • 定义为false的常量:None和false。
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • 0、0、0、0j、小数(0)、分数(0、1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)
  • 空序列和集合:“,(),[],{},set(), range(0)

And the datamodel documentation:

和datamodel文档:

object.__bool__(self)

object.__bool__(自我)

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.

调用实现真值测试和内置操作bool();应该返回False或True。当没有定义该方法时,如果定义了__len__(),则调用__len__();如果定义了该方法,则如果结果为非零,则认为该对象为真。如果一个类既没有定义__len__()也没有定义__bool__(),那么它的所有实例都被认为是正确的。

and

object.__len__(self)

object.__len__(自我)

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.

调用来实现内置函数len()。应该返回对象的长度,一个整数>= 0。另外,在布尔上下文中,不定义__bool__()方法且其__len__()方法返回零的对象被认为是假的。

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.

我们可以看到,使用内建函数len与0进行长度检查,或者使用空列表进行检查,都比使用有文档说明的语言内建语法要低得多。

Why?

为什么?

For the len(a) == 0 check:

对于len(a) = 0检查:

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

首先Python必须检查全局,看看len是否被跟踪。

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

然后它必须调用函数,load 0,并在Python中进行相等比较(而不是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)

对于[]=[],它必须构建一个不必要的列表,然后在Python的虚拟机(与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:

“python”方法是一种更简单、更快速的检查方法,因为列表的长度被缓存在对象实例头中:

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

Evidence from the C source and documentation

PyVarObject

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.

这是PyObject的扩展,它添加了ob_size字段。这只用于具有长度概念的对象。这种类型通常不会出现在Python/C API中。它对应于PyObject_VAR_HEAD宏展开所定义的字段。

From the c source in Include/listobject.h:

从包含/列表项中的c来源:

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.

我很喜欢研究这个问题,我花了很多时间整理我的答案。如果你认为我遗漏了什么,请在评论中告诉我。

#8


61  

I have seen the below as preferred:

我认为以下是我的首选:

if not a:
    print("The list is empty or null")

#9


48  

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.

似乎没有人会在一开始就质疑你是否需要测试这份清单。由于您没有提供额外的上下文,我可以想象您可能首先不需要做这个检查,但是不熟悉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.

这可以处理a的任何内容,而不需要对空性进行特定的检查。如果a是空的,则依赖块将不会执行,解释器将会掉到下一行。

If you do actually need to check the array for emptiness, the other answers are sufficient.

如果你确实需要检查空的数组,其他的答案就足够了。

#10


44  

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.

len()是Python列表、字符串、dicts和set的O(1)操作。Python在内部跟踪这些容器中的元素数量。

JavaScript has a similar notion of truthy/falsy.

JavaScript也有类似的truthy/falsy的概念。

#11


27  

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:

被选为1。我不确定这是不是因为读者反对这一策略,或者认为答案毫无帮助。我将假设它是后者,因为-- --不管什么叫“毕达哥拉斯式”---这是正确的策略。除非您已经排除了,或者准备处理a为False的情况,否则您需要进行比a为非a的更严格的测试。你可以用这样的东西:

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:

第一个测试是对上面@Mike的回答的回应。第三行也可以改为:

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.

你可以没有显式类型检查,如果周围的环境已经向你保证是一个值类型的你准备处理,或者如果你确定类型不准备处理会提高错误(例如,TypeError如果你叫len值的定义),你准备处理。一般来说,“python”的约定似乎是这样的。像鸭子一样挤它,如果它不知道如何嘎嘎叫,就让它发出鸭子的叫声。你仍然需要考虑你所做的类型假设,以及你没有准备好处理的情况是否真的会在正确的地方出错。Numpy数组是一个很好的例子,它只是盲目地依赖len或布尔型类型,可能无法精确地完成您所期望的工作。

#12


24  

Python is very uniform about the treatment of emptiness. Given the following:

对于空的处理,Python是非常统一的。鉴于以下几点:

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.

您只需用“if”语句检查列表a,看看它是否为空。从我所读到的和学到的内容来看,这是一种“python化”的方式,可以查看列表或元组是否为空。

#13


18  

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.
  • 任何数字类型的零,例如,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.
  • 用户定义类的实例,如果类定义了__bool__()或__len__()方法,当该方法返回整数值0或bool值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!')

#14


15  

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

以下是一些检查列表是否为空的方法:

a = [] #the list

1) The pretty simple pythonic way:

1)简单的毕达哥拉斯式:

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.

在Python中,诸如列表、元组、集合、命令、变量等空容器被视为假的。可以简单地将列表视为谓词(返回布尔值)。一个真值表示它是非空的。

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

2)一种非常明确的方法:使用len()查找长度并检查它是否等于0:

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

3) Or comparing it to an anonymous empty list:

3)或将其与匿名空列表进行比较:

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

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

4)另一种愚蠢的方法是使用exception和iter():

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

#15


13  

Some methods that I use:

我使用的一些方法:

if not a:
    print "list is empty"


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

#16


5  

I prefer the following:

我更喜欢下面的:

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

Readable and you don't have to worry about calling a function like len() to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unless a was gigantic.

可读,您不必担心调用像len()这样的函数来迭代变量。虽然我不太确定这种东西的BigO符号是什么。但是Python的速度如此之快,我怀疑它是否重要,除非a是巨大的。

#17


5  

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

#18


2  

Another simple way could be

另一个简单的方法是

a = []
if len(a) == 0:
  print("Empty")
else:
  print(" Not empty")

#19


1  

You can even try using bool() like this

您甚至可以尝试像这样使用bool()

    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.

非常方便和有用的。

#20


1  

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.

#21


0  

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

受到@dubiousjim的解决方案的启发,我建议使用一个额外的通用检查,看看它是否是可迭代的

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

注意:字符串被认为是可迭代的。-如果要排除空字符串,则添加而不是isinstance(a,(str,unicode))

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

#22


0  

Simply use is_empty() or make function like:-

只需使用is_empty()或使函数如:-

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

它可以用于任何data_structure,如列表、元组、字典等。通过这些,您可以使用is_empty(any_structure)多次调用它。

#23


-1  

An unofficial approach :

一个非官方的方式:

 a = []
 try:
  print(a[-1])
 except IndexError:
  print("List is empty")

#24


-1  

Look at the following code executed on Python interactive terminal.

查看在Python交互式终端上执行的以下代码。

>>> a = []
>>> if a:
...     print "List is not empty";
... else:
...     print "List is empty"
... 
List is empty
>>> 
>>> a = [1, 4, 9]
>>> if a:
...     print "List is not empty";
... else:
...     print "List is empty"
... 
List is not empty
>>> 

#25


-1  

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

空列表的真值为False,而非空列表的真值为True。

#26


-3  

i think people suggested for

我认为人们建议

if len(list1) == 0:
    print("is a good way")

or len you can count by

或者你可以用len (count by)

if list1.__ len__()==0:
    print("list1 is empty")

you can use one more way

你可以再用一种方法

if list1.__ sizeof__() == 40:
    print("list1 is empty")

size of empty list is always 40.

空列表的大小总是40。