[Tutor] Testing for empty list

Alan Gauld alan.gauld at btinternet.com
Mon Oct 19 21:01:58 CEST 2009


"Katt" <the_only_katala at verizon.net> wrote

> Just a newbie question, but when would you test for an empty list?  

When you are processing a list such that you are deleting items as you go.
When the list is empty stop processing!

And Python helps you do that by treating an empty list as a False 
boolean value so you can do

while myList:
     process items from myList

This will keep on processing myList until all the items have 
been deleted. Note, this could be more times than the number 
of items in the list...for example:

counter = 0
myList = [12,24]
nines = []
while myList:
     counter += 1
     print "iteration number", counter
     index = 0
     while index < len(myList):    # copes with disappearing members
              if myList[index]  % 9 == 0: # is it divisible by 9?
                 nines.append(myList[index])
                 del(myList[index])     # remove from list
              else: myList[index] -= 1
              index += 1 
print nines

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

That is the same as

while mylist:
      continue program
else:
      print 'mylist is empty'

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list