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 04:59

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.

查看更多
与君花间醉酒
3楼-- · 2018-12-31 05:00

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
查看更多
谁念西风独自凉
4楼-- · 2018-12-31 05:01

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.

查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 05:02
print('not empty' if a else 'empty')

a little more practical:

a.pop() if a else None
查看更多
回忆,回不去的记忆
6楼-- · 2018-12-31 05:02

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

查看更多
路过你的时光
7楼-- · 2018-12-31 05:03
if not a:
  print("List is empty")

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

查看更多
登录 后发表回答