[Tutor] Testing for empty list

Rich Lovely roadierich at googlemail.com
Mon Oct 19 17:32:54 CEST 2009

2009/10/19 Katt <the_only_katala at verizon.net>
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

There's various situations, consider this simple implementation of a
queue of tasks that need completing:

from abc import abstractmethod

class QueueableItem(object):
    """abstract base class to allow tasks to be queued"""
    def queue(self):
        """Add the task to the queue"""
    def completed(self):
        """Mark the task as completed, and remove it from the queue"""
    def run(self, *args):
        """complete the queued task, should call self.completed()
after running."""

class PrintTask(QueueableItem):
    def __init__(self, data):
        self.data = data
    def run(self, *args):
        print self.data

def processQueue():
    while queue:
    print "Queue Processed\n"

if __name__ == "__main__":
    queue = []

In this situtation, the while loop could be substituted for a for
loop, but consider the following task:

class TaskThePrecedent(QueueableItem):
    def run(self, *args):
        if precedentCompleted():
            #do stuff
             queue.insert(0, PrecedentTask())

Yes, the precedentTask code could be pasted into the else block, but
what if more than one class used that precedent, or the precedent had
precedents itself, which in turn were used by multiple classes?

OK, That was pretty contrieved, and I'm sure other tutors can come up
with better examples, but I think it gives an idea of one of the many
situtations in which you might need to test for a lists contents.

I also put far too much work into it.  "Simple", my foot.

Rich "Roadie Rich" Lovely

There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.

More information about the Tutor mailing list