5

What is the most effective way to check if a list contains only empty values (not if a list is empty, but a list of empty elements)? I am using the famously pythonic implicit booleaness method in a for loop:

def checkEmpty(lst):
    for element in lst:
        if element:
            return False
            break
    else:
        return True

Anything better around?

4 Answers 4

16
if not any(lst):
    # ...

Should work. any() returns True if any element of the iterable it is passed evaluates True. Equivalent to:

def my_any(iterable):
    for i in iterable:
        if i:
            return True
    return False
Sign up to request clarification or add additional context in comments.

2 Comments

Seems to be the most elegant approach :-)
I agree, this is nice and clean.
3
len([i for i in lst if i]) == 0

Comments

2

Using all:

   if all(item is not None for i in list):
      return True
    else:
      return False

4 Comments

I think all's brother any feels slighted.
@StevenRumbalski I like the shorter approach using any, but I thought I would throw in my two cents for an alternate idea.
Depending on the OP's definition of "empty", not bool(item) may be better than item is not None.
@StevenRumbalski Thanks for the edit, you can change whatever you find to be suitable.
1
>>> l = ['', '', '', '']
>>> bool([_ for _ in l if _])
False
>>> l = ['', '', '', '', 1]
>>> bool([_ for _ in l if _])
True

2 Comments

This is a bit awkward looking and it doesn't short circuit like not any(l).
I agree that this solution is far from optimal :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.