What way is the best to check an empty list?
Steve Holden
steve at holdenweb.com
Wed Mar 25 23:31:05 EDT 2009
Stef Mientki wrote:
> andrew cooke wrote:
>> Andre Engels wrote:
>>
>>> On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke <andrew at acooke.org> wrote:
>>>
>>>> i will go against the grain slightly and say that "len" is probably the
>>>> best compromise in most situations (although i admit i don't know what
>>>>
>> [...]
>>
>>>> but i may be wrong - are there any containers (apart from pathological
>>>> hand-crafted examples) that would not define __len__()?
>>>>
>>> When writing my answer, I thought of generators, but I now find that
>>> those will have boolean value 'true' whether or not they have
>>> something to generate, so they will go wrong under either method. The
>>> same holds for iterators. So for now I can't find any good example.
>>>
>>
>>
>> actually, the implication of what you said is probably worth emphasising
>> to the original poster: often you don't need to test whether a list is
>> empty or not, you simply iterate over its contents:
>>
>> for x in foo:
>> # do something
>>
>> this will then work with lists, tuples, sets, but also with iterators and
>> generators (which would give incorrect results in a test). in all cases,
>> "do something" will not happen if there are no data to process.
>>
> Now it would be nice to allow iteration over others too, like None .
> a = None
> for item in a :
> do_something_with_item
>
To me that makes about as much sense as writing
for x in 1.0:
print x
and expecting it to print 1.0. Numbers just aren't iterable. Neither is
None. A TypeError exception is the only appropriate response.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/
More information about the Python-list
mailing list