[Tutor] Testing for empty list

Katt the_only_katala at verizon.net
Mon Oct 19 16:44:36 CEST 2009


> Wayne wrote:
>> Hi, I think I recall seeing this here, but I wanted to make sure I'm
>> correct.
>> Is the best way to test for an empty list just test for the truth value?
>> I.e.
>>
>> mylist = [1,2,3]
>>
>> while mylist:
>>    print mylist.pop()
>>
>> Thanks,
>> Wayne
>>
>>
> My take is simple:  Use the above form if you *know* that mylist is in
> fact a list.  If you don't know its type for sure (the name is a clue,
> but not conclusive ;-) ) then use a more specific test.
>
> In your case, you know it's a list, or least something that supports
> pop().  So your form should be great.
>
> DaveA
>

Hello all,

Just a newbie question, but when would you test for an empty list?  Is it 
part of a code error detection or an error check to make sure that there is 
user input?

Couldn't you just use something like:

while len(mylist) > 0:
    continue program
else:
    print "mylist is empty

or is my lack of python knowledge preventing me from seeing the meaning of 
the question?

Thanks in advance,

Katt 



More information about the Tutor mailing list