Which is the best way...

Matthew D. Wood woodm at equire.com
Wed Aug 15 22:54:35 CEST 2001


I have an interesting code-correctness question.  I firmly believe in 
doing things 'The Right Way' and I'm not sure which of these 3 blocks is 
better.  So, if you code-guru's could help me out I would definitely 
appreciate it.



###################################################

#!/usr/bin/env python

list_a = ['a', 'b', 'e', 'c', 'd']
list_b = ['a', 'b', 'c', 'd', 'e']


# Will fail if list *is* in order
def first_non_ordered_dumb (my_list) :
       for index in range(len(my_list)) :
               if my_list[index] > my_list[index + 1] :
                       return index - 1


# Works, but I do that 'if' for every element
# Even though I know that it only matters on the last one.
def first_non_ordered_1 (my_list) :
       last_index = len(my_list) - 1
       for index in range(len(my_list)) :
               if index == last_index :
                       return None

               if my_list[index] > my_list[index + 1] :
                       return index + 1


# Works, but how much overhead is there in the slicing of the range list?
def first_non_ordered_2 (my_list) :
       for index in range(len(my_list))[:-1] :
               if my_list[index] > my_list[index + 1] :
                       return index + 1

       else :
               return None


# Works, but how efficient is the try-except stuff
# when compared to the two above?
def first_non_ordered_3 (my_list) :
       try :
               for index in range(len(my_list)) :
                      if my_list[index] > my_list[index + 1] :
                               return index + 1

       except IndexError :
               return None



for my_list in (list_a, list_b) :
       print my_list
       #print 'dumb:', first_non_ordered_dumb(my_list)
       print '1:', first_non_ordered_1(my_list)
       print '2:', first_non_ordered_2(my_list)
       print '3:', first_non_ordered_3(my_list)


#########################################

I guess I could do it with a while loop, but that always seemed messy.  
A 'C for loop' would work better than a 'python for loop' here, and 
usually that seems to indicate a 'while loop' should be used in python.  
But I MUCH prefer 'for loops' to 'while loops'.  What do you guys think?

Or, as is usually the case, did I miss something that makes the problem 
much easier.





More information about the Python-list mailing list