checking if a list is empty
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 6 22:49:53 EDT 2011
On Fri, 06 May 2011 16:05:09 -0400, Adam Tauno Williams wrote:
> I'd never accept code like "if not x" as an empty test.
So much the worse for you then.
The point of the "if x" idiom is that it is a polymorphic test which is
independent of the type. It works with any non-broken object[1], no
matter what x is, since it allows x to decide for itself whether it is
empty or not.
Of course, you can write your own polymorphic test:
try:
flag = len(x) == 0
except TypeError:
# This *should* succeed, for anything not broken. If not, we can't
# recover, so just let the exception propagate.
flag = bool(x)
# Hilariously, bool(x) may also try len(x) == 0... oh well.
if flag:
...
Congratulations! You've now found a way to write "if x:" in five lines,
53 characters (plus whitespace and comments) and an extraneous variable
polluting the namespace. If you're being paid per line of code, this is a
good win.
Of course, sometimes you don't want polymorphism (or at least, not too
much polymorphism). Sometimes I'll write "if x == 0" or similar if I want
to emphasize that x is a special case unrelated to the truth/falseness of
x. But that's quite rare. Normally I trust x to decide for itself whether
it is empty or not.
[1] Arguably with the exception of iterables. But then the len(x) test
doesn't work for them either.
--
Steven
More information about the Python-list
mailing list