the list.index(x)
function returns the index in the list of the first item whose value is x
.
is there a function, list_func_index()
, similar to the index()
function that has a function, f()
, as a parameter. the function, f()
is run on every element, e
, of the list until f(e)
returns True
. then list_func_index()
returns the index of e
.
codewise:
>>> def list_func_index(lst, func):
for i in range(len(lst)):
if func(lst[i]):
return i
raise ValueError('no element making func True')
>>> l = [8,10,4,5,7]
>>> def is_odd(x): return x % 2 != 0
>>> list_func_index(l,is_odd)
3
is there a more elegant solution? (and a better name for the function)