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
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
-
1Seems to be the most elegant approach :-)Dr. Jan-Philip Gehrcke– Dr. Jan-Philip Gehrcke08/30/2012 15:47:11Commented Aug 30, 2012 at 15:47
-
I agree, this is nice and clean.squiguy– squiguy08/30/2012 15:52:26Commented Aug 30, 2012 at 15:52
len([i for i in lst if i]) == 0
answered Aug 30, 2012 at 15:45
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
-
I think
all
's brotherany
feels slighted.Steven Rumbalski– Steven Rumbalski08/30/2012 15:50:26Commented 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.squiguy– squiguy08/30/2012 15:51:41Commented Aug 30, 2012 at 15:51
-
1Depending on the OP's definition of "empty",
not bool(item)
may be better thanitem is not None
.Steven Rumbalski– Steven Rumbalski08/30/2012 15:58:44Commented Aug 30, 2012 at 15:58 -
@StevenRumbalski Thanks for the edit, you can change whatever you find to be suitable.squiguy– squiguy08/30/2012 16:00:33Commented Aug 30, 2012 at 16:00
>>> l = ['', '', '', '']
>>> bool([_ for _ in l if _])
False
>>> l = ['', '', '', '', 1]
>>> bool([_ for _ in l if _])
True
answered Aug 30, 2012 at 15:45
-
This is a bit awkward looking and it doesn't short circuit like
not any(l)
.Steven Rumbalski– Steven Rumbalski08/30/2012 15:55:47Commented Aug 30, 2012 at 15:55 -
I agree that this solution is far from optimal :)Dr. Jan-Philip Gehrcke– Dr. Jan-Philip Gehrcke08/30/2012 15:57:42Commented Aug 30, 2012 at 15:57
lang-py