Checking if elements are empty

Neil Cerutti horpner at yahoo.com
Mon Sep 10 11:24:37 EDT 2007


On 2007-09-10, Chris Mellon <arkanes at gmail.com> wrote:
> 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.

Agreed; but I prefer 'if y[0] == ""', absent more context and
better names.

-- 
Neil Cerutti



More information about the Python-list mailing list