checking if a list is empty
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat May 7 04:28:56 EDT 2011
On Fri, 06 May 2011 14:49:24 -0500, harrismh777 wrote:
> Terry Reedy wrote:
>>>> (2) if not li:
>>>
>>> This is fine.
>>
>> This is the intended way. Anything in addition is extra noise and
>> wasted calculation. In other words, let Python do the boilerplate work
>> for you.
>
> I agree, but I don't like it.
>
> ... if not li says nothing about what li is supposed to 'be'
Yes, and? Neither does:
isempty(li) # li could be anything that polymorphic isempty can deal with
li.isempty() # li could be anything with a "isempty" method
len(li) == 0 # li could be anything with a length (list, dict, set, ...)
That's duck-typing for you, and it is generally a strength rather than a
weakness. For those times when it is a weakness, that's where we have
naming conventions, type-testing, and (in some languages) static types.
> and implies in any case that li does not exist
It does nothing of the sort. If li doesn't exist, you get a NameError.
> or worse is some kind of boolean.
Only if you're still thinking in some language that isn't Python.
Boolean tests in Python are polymorphic. bool() exists mainly to provide
a canonical representation of true and false values, not because you are
limited to using booleans in truth-testing. Far from it: it is often very
useful to do something like this:
settings = local_settings or global_settings or builtin_settings
where the first non-empty *_settings wins.
> li is in fact an empty list [] and will identify as such, and of
> course (as a list object) has all of the attributes and methods of a
> list...
>
> Why not have a list method that makes this more explicit:
For the same reason that we don't have an int method that makes zero
testing more explicit:
n = 0
n.iszero() # returns True
Because sometimes you can have too much explicitness.
--
Steven
More information about the Python-list
mailing list