16 November 2010

The best way of checking empty list or dict in Python

There must be an idiom for this task. Here is how I test such conditions:

d = {} # an empty dictionary
l = [] # an empty list

bool(len(l)) # False
not len(l)   # True

bool(len(d)) # False
not len(d)   # True


Or, an even neater way to do it:


d = {} # an empty dictionary
l = [] # an empty list

bool(d) # False, the empty dict is converted to bool directly!
not d   # True

# So, you can have something like this:

if not d: doSomething()

No comments: