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:08

I have seen the below as preferred:

if not a:
    print("The list is empty or null")
查看更多
牵手、夕阳
3楼-- · 2018-12-31 05:08

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")
查看更多
有味是清欢
4楼-- · 2018-12-31 05:10

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.

查看更多
无色无味的生活
5楼-- · 2018-12-31 05:10

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

查看更多
骚的不知所云
6楼-- · 2018-12-31 05:10

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

查看更多
梦醉为红颜
7楼-- · 2018-12-31 05:12

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.

查看更多
登录 后发表回答