Pythonic emptiness checking

Sibylle Koczian nulla.epistola at web.de
Wed Apr 29 09:51:15 EDT 2009


Filip Gruszczyński schrieb:
> One of the Python Zen rules is Explicit is better implicit. And yet
> it's ok to do:
> 
> if x:
>    do_sth
> 
> when x is string or list. Since it's very comfy, I've got nothing
> against though. I am just curious, why is it so?
> 
> And one more thing: is it ok to do
> 
> if x:
> 
> instead of
> 
> if x is not None:
> 
> Because I often encounter it and would like to know, if I can simplify
> it. Especially that I liked similar construction in C/C++.
> 
Depends on what you need. If your x is 0 or 0.0, '', the empty list,
dictionary or set, or a class instance with __len__ 0 or __nonzero__
false, then x is false, but "x is not None" is true.

HTH
Sibylle




More information about the Python-list mailing list