Which is the best way...

Alex Martelli aleaxit at yahoo.com
Wed Aug 15 17:30:02 EDT 2001


"Matthew D. Wood" <woodm at equire.com> wrote in message
news:mailman.997909164.1727.python-list at python.org...
    ...
> # Will fail if list *is* in order
> def first_non_ordered_dumb (my_list) :
>        for index in range(len(my_list)) :
use instead:
          for index in range(len(my_list)-1):
>                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?

more than needed...

> def first_non_ordered_2 (my_list) :
>        for index in range(len(my_list))[:-1] :
use instead:
          for index in range(len(my_list)-1):
for the same effect obtained more effectively:-).

Note that this becomes equal to the first solution
when both are corrected (one for correctness, one
for speed) apart from a few minor things:

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

first version returned index - 1 (range -1 up) while
this one returns index + 1 (range +1 up), probably
what's wanted.

>        else :
>                return None

redundant, better to eliminate these two lines.


Alex






More information about the Python-list mailing list