Search code examples
pythonstringpython-3.xlistempty-list

Detect empty list vs list of empty strings


I am new to Python, and I have searched for solution for detecting empty list. Say we have an empty string, like:

a = ''
if not a:
    print('a is empty')

This works fine. However, my problem arises when:

a = ['','','']
if not a:
    print('a is empty')

This one does not work. What is the Pythonic way of detecting a which I guess is a list containing empty strings in the above case?

Thanks in advance for your comments and suggestions.


Solution

  • A list is only empty if it has no members. It has members, but they're empty, it still has members, so it's still truthy.


    If you want to test whether all of the members of a list are empty, you can write it like this:

    if all(not element for element in a):
        print('a is made of empty things')
    

    The all function should be pretty obvious. The argument to it might not be. It's a generator expression—if you've never seen one, first read about list comprehensions, then iterators and the following two sections.


    Or you can turn it around and test whether not any of the members are not empty:

    if not any(a):
        print('a is made of empty things')
    

    The double negative seems a bit harder to understand. But on the other hand, it means you don't need to understand a generator expression (because (element for element in a) is just the same thing as a, so we can keep it simple).

    (And, as PM 2Ring points out, this one probably a little faster, although probably not enough to matter for most uses.)