Checking if elements are empty

Chris Mellon arkanes at gmail.com
Mon Sep 10 10:24:12 EDT 2007


On 9/10/07, Neil Cerutti <horpner at yahoo.com> wrote:
> On 2007-09-08, Wildemar Wildenburger <lasses_weil at klapptsowieso.net> wrote:
> > Lawrence D'Oliveiro wrote:
> >>>>> if y[0]:
> >>>> Not a good idea.
> >>> Why not?
> >>
> >> Because there is a situation where your version of the test
> >> will fail even if the first element of y is non-null.
> >
> > Such as? Seriously people, a little more verbosity wouldn't
> > hurt here. This isn't a mystery game.
>
> >>> if "": True
> ...
> >>> if 0: True
> ...
> >>> if []: True
> ...
> >>> if {}: True
> ...
> >>> if None: True
> ...
>
> That's may not be all the possibilities. Lots of Python objects
> can evaluate to false in a boolean context.
>

All of these except 0 and None will also return False if you check the
length. In fact, I am not aware of any builtin where len() will return
0, but it will be true in a boolean context.

If you're advocating being more specific in the hope of catching
errors, this is a pretty terrible example. The OP wasn't checking for
"null", whatever that means - he was checking for the empty string, in
a list known (or intended) to contain only strings. The simple boolean
check is totally appropriate.



More information about the Python-list mailing list