tags:

views:

127

answers:

3

I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.

Is there a single line way to do the following (not including the print)?

l = [{},{},{}] # this list is generated elsewhere...
all_empty = True
for i in l:
  if i:
    all_empty = False

print all_empty

Somewhat new to python... I don't know if there is a shorthand built-in way to check this. Thanks in advance.

+10  A: 
all(not d for d in l)
Jimmy
Worked like a charm. Thanks.
Brant
Also `all( len(d) == 0 for d in l)`, which is more detailed on what "empty" means.
S.Lott
More detailed doesn't mean more pythonic, that's why I'd prefer Jimmy's version.
jae
+8  A: 

not any(d for d in l) is equivalent by De Morgan's Law to all(not d for d in l), but applies just one not operator. The short-circuiting behavior is also equivalent.

Edit 1: the inner genexp is actually (innocuous but) redundant: not any(l) is faster and more concise.

Edit 2: a comment claims that all(not d for d in l) is "more what you want to express" than not any(l), and I strongly disagree: even in natural language, "all items of the list are unpopulated" isn't any more normal, direct or clear than "no item of the list is populated" -- beyond the absolute logical equivalence by the laws of logic, the two ways of expression are very close and roughly equivalent in terms of human psychology, too.

Alex Martelli
"not any(l)" is sufficient.
unbeknown
Wow, someone one-upped the martellibot ;D
jae
Though, it's the old conundrum: Jimmy's is close to what you actually want to express (all of the empty), while `not any(l)` is (probably, haven't measured it) faster.
jae
@unbeknown, right -- the inner genexp is (innocuous but) redundant, editing to point it out. @jae, why's "no item is populated" any more "what you actually want to express" than "all items are unpopulated"? They're roughly equivalent in natural language and thinking patterns as well as identically so by the laws of logic.
Alex Martelli
@Alex Martelli: in Python, I like the way "not any(l)" reads vs "all(not d for d in l)", but in English, "all are empty" is what I'd write first, compared to "none are not empty." "populated" and "unpopulated" are big enough words to obscure that distinction.
Jimmy
"true" and "false" (which translate to "non-empty" or "populated", and "emptyO or "non-populated", respectively, for containers -- but in other ways for non-containers) are better (and monosyllabic!-) choices -- the use of `not` clearly focuses the mind on truthiness, not emptyhood;-). So the pick is between "all are false" vs "none are true", which, again, is really a wash.
Alex Martelli
+7  A: 

not any(d for d in l) could be shortened to just not any(l) in this case.

Brendan Abel