1

This works:

def find_file_ix(fn,fn_list):
   
    if fn in fn_list:
        ix=fn_list.index(fn)
    else:
        ix=-1
    return ix

l=['a','b','c','d','e']

print(find_file_ix('d',l))
print(find_file_ix('z',l))

and prints 3, -1 as expected.

I could accomplish the same thing with a try/except sequence. However, I find both clumsy and the above code seems to have an element of redundancy - surely the 'in' test must have already found the index?

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • Check out: [Fastest way to check if a value exists in a list](https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exists-in-a-list/58844693#58844693) – DarrylG Oct 18 '21 at 10:41
  • While using *-1* as an indicator of an unexpected event is perfectly fine, it is error prone because *-1* is a valid index in python. I think *try* is safer and more pythonic in this case. The *in* operator could return the index for lists, but not for other collection types that don't support indexing. – Michael Szczesny Oct 18 '21 at 10:53
  • Thanks Michael. I actually modelled the -1 on the way that find works. I can see the danger. (I am an old assembly language, Fortran, Cobol - a touch of Pascal - programmer who is learning Python for fun. It is sometimes hard to work out what the 'best' way of doing something is. 'Best' can mean 'most elegant', 'quickest', 'most understandable', 'safest' ... I appreciate all the help I can get!) – Bill Cairns Oct 18 '21 at 15:28

0 Answers0