[Tutor] Testing for empty list

Alan Gauld alan.gauld at btinternet.com
Mon Oct 19 09:37:37 CEST 2009

"Todd Matsumoto" <tmatsumoto at gmx.net> wrote

> The while loop will print each index of the list.

No, the while does nothing with list indexes, that is entirely
down to the programmer. The while loop simply repeats for
as long as its test expression evaluates to True.

> As far as I know there isn't any 'True' or 'False' output from a list.

Lists are considered True if they are non empty, in the
same way as strings.

So the OPs test is perfectly valid

while myList:
     do something to reduce mylist
     (or use break but then you should use while True)

> If you want to do something if mylist is empty you can check it like 
> this:
> if not mylist:
>   ... do something ...

Which is the logical inverse of what the OP was testing
in his while loop.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list