10

I am looking for a built-in/library function or method in Python that searches a list for a certain element that satisfies a predicate and returns the index. I'm looking for a built-in function because I feel that this should be in the Python libraries.

It is similar to, e.g. [(10, 1), (20, 2), (30, 3)].index((30, 3)) that returns 2, but I want a custom comparison function, for example, I just want to match the first element of the tuple in the earlier example.

What I am looking is a function that essentially does this:

def custom_index(l, f):
    for i, e in enumerate(l):
         if f(e): return i
    return -1 # or something else to indicate not found

Usage:

custom_index([(10, 1), (20, 2), (30, 3)], lambda x: x[0]==30) -> returns 2
Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228
  • The answers to the possible dupe suggest that there is no such built-in/library function – Leon Dec 08 '16 at 11:34
  • @Leon The question you linked wants the item itself, yuku wants the item's index. – PM 2Ring Dec 08 '16 at 11:36
  • 3
    I'm pretty sure that there's no standard library function that does this. FWIW, here's your function made into a one-liner: `def custom_index(l, f): return next((i for i, e in enumerate(l) if f(e)), -1)` – PM 2Ring Dec 08 '16 at 11:37

2 Answers2

4

There's not such a built-in function, but here's another possible version of the function you're looking for:

def custom_index(it, f, default=-1):
    return next((i for i, e in enumerate(it) if f(e)), default)
Francisco
  • 10,918
  • 6
  • 34
  • 45
2

You can still use Python index function with the help of list comprehension

l = [(10, 1), (20, 2), (30, 3)]
[t[0] for t in l].index(30)
Vaishali
  • 37,545
  • 5
  • 58
  • 86