Skip to content
Advertisement

Python: return the index of the first element of a list which makes a passed function true

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:

JavaScript

Is there a more elegant solution? (and a better name for the function)

Advertisement

Answer

You could do that in a one-liner using generators:

JavaScript

The nice thing about generators is that they only compute up to the requested amount. So requesting the first two indices is (almost) just as easy:

JavaScript

Though, expect a StopIteration exception after the last index (that is how generators work). This is also convenient in your “take-first” approach, to know that no such value was found — the list.index() function would throw ValueError here.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement