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?

asked Aug 30, 2012 at 15:43

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
answered Aug 30, 2012 at 15:45
2
  • 1
    Seems to be the most elegant approach :-) Commented Aug 30, 2012 at 15:47
  • I agree, this is nice and clean. Commented Aug 30, 2012 at 15:52
3
len([i for i in lst if i]) == 0
answered Aug 30, 2012 at 15:45
2

Using all:

 if all(item is not None for i in list):
 return True
 else:
 return False
Steven Rumbalski
45.7k10 gold badges96 silver badges125 bronze badges
answered Aug 30, 2012 at 15:47
4
  • I think all's brother any feels slighted. Commented Aug 30, 2012 at 15:50
  • @StevenRumbalski I like the shorter approach using any, but I thought I would throw in my two cents for an alternate idea. Commented Aug 30, 2012 at 15:51
  • 1
    Depending on the OP's definition of "empty", not bool(item) may be better than item is not None. Commented Aug 30, 2012 at 15:58
  • @StevenRumbalski Thanks for the edit, you can change whatever you find to be suitable. Commented Aug 30, 2012 at 16:00
1
>>> l = ['', '', '', '']
>>> bool([_ for _ in l if _])
False
>>> l = ['', '', '', '', 1]
>>> bool([_ for _ in l if _])
True
answered Aug 30, 2012 at 15:45
2
  • This is a bit awkward looking and it doesn't short circuit like not any(l). Commented Aug 30, 2012 at 15:55
  • I agree that this solution is far from optimal :) Commented Aug 30, 2012 at 15:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.