Checking if elements are empty

Wildemar Wildenburger lasses_weil at klapptsowieso.net
Fri Sep 7 09:45:30 EDT 2007


Steven D'Aprano wrote:
> On Fri, 07 Sep 2007 11:12:05 +0200, Wildemar Wildenburger wrote:
> 
>> Lawrence D'Oliveiro wrote:
>>> In message <mailman.93.1189003016.2658.python-list at python.org>, Chris
>>> Mellon wrote:
>>>
>>>> On 9/5/07, Steve Holden <steve at holdenweb.com> wrote:
>>>>> Doran, Harold wrote:
>>>>>> Is there a way to check if the first element of y is null?
>>>>>>
>>>>> len(y[0]) == 0
>>>>>
>>>> Better spelled as
>>>>
>>>> if y[0]:
>>> Not a good idea.
>> Why not?
> 
> 
> What happens if y is an empty list?
> 
> 
An exception pops up, of course ;).

It all depends on the (intended) semantics of the program; the original 
question sounds like that list is supposed to have at least one element 
at that point, so there is no problem. And if it's not then that has to 
be dealt with, but that is not the problem here.
So the usual way to check if the first element of a list y is True in a 
boolean context is indeed "if y[0]:" (or for False of course "if not 
y[0]:").

/W



More information about the Python-list mailing list