Which is the best way...
Jeff Shannon
jeff at ccvcorp.com
Wed Aug 15 20:03:15 EDT 2001
"Matthew D. Wood" wrote:
> 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.
>
[trimming code]
>
> 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
>
> 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
These two are, IMHO, the best options, though I'd probably do this--
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
# note that, by dropping off the for-loop, and off the function, we
implicitly return None
# so the following line is optional
return None
Not that I'm in any danger of being called a code-guru any time soon. ;)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list