开发者

Python: Check if all dictionaries in list are empty

开发者 https://www.devze.com 2022-12-23 18:19 出处:网络
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.

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 t开发者_开发技巧he 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.


all(not d for d in l)


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号