120

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)

wjandrea
  • 28,235
  • 9
  • 60
  • 81
bandana
  • 3,422
  • 6
  • 26
  • 30

7 Answers7

163

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

next(i for i,v in enumerate(l) if is_odd(v))

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:

y = (i for i,v in enumerate(l) if is_odd(v))
x1 = next(y)
x2 = next(y)

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 raise ValueError here.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Paul
  • 2,862
  • 3
  • 18
  • 18
  • 15
    This isn't obfuscatory - or at least, it's not any more obfuscatory than using `map(f, seq)` instead of `[f(x) for x in seq]` is. In other words, it's idiomatic. And like other idioms, it's not straightforward until it's part of your vocabulary. – Robert Rossney Nov 09 '09 at 21:41
  • 3
    just a reminder to catch `StopIteration` if the end condition might not be met. – payala Aug 30 '18 at 18:37
  • 14
    Small hint: `next` accepts a second argument that will be returned in case of no match, instead of raising `StopIteration`. – bgusach Apr 03 '20 at 15:18
24

One possibility is the built-in enumerate function:

def index_of_first(lst, pred):
    for i, v in enumerate(lst):
        if pred(v):
            return i
    return None

It's typical to refer a function like the one you describe as a "predicate"; it returns true or false for some question. That's why I call it pred in my example.

I also think it would be better form to return None, since that's the real answer to the question. The caller can choose to explode on None, if required.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
16

Paul's accepted answer is best, but here's a little lateral-thinking variant, mostly for amusement and instruction purposes...:

>>> class X(object):
...   def __init__(self, pred): self.pred = pred
...   def __eq__(self, other): return self.pred(other)
... 
>>> l = [8,10,4,5,7]
>>> def is_odd(x): return x % 2 != 0
... 
>>> l.index(X(is_odd))
3

essentially, X's purpose is to change the meaning of "equality" from the normal one to "satisfies this predicate", thereby allowing the use of predicates in all kinds of situations that are defined as checking for equality -- for example, it would also let you code, instead of if any(is_odd(x) for x in l):, the shorter if X(is_odd) in l:, and so forth.

Worth using? Not when a more explicit approach like that taken by @Paul is just as handy (especially when changed to use the new, shiny built-in next function rather than the older, less appropriate .next method, as I suggest in a comment to that answer), but there are other situations where it (or other variants of the idea "tweak the meaning of equality", and maybe other comparators and/or hashing) may be appropriate. Mostly, worth knowing about the idea, to avoid having to invent it from scratch one day.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Nice one! But what would we "name" X? Something like "Key" perhaps? Because it reminds me of l.sort(key=fn). – Paul Nov 09 '09 at 16:24
  • You could almost call it "Equals", so the line reads l.index(Equals(is_odd)) – tgray Nov 09 '09 at 16:34
  • 5
    I think that what Alex (implicitly) suggested, `Satisfies`, is a good name for it. – Robert Rossney Nov 09 '09 at 21:43
  • @Robert, I do like Satisfies! – Alex Martelli Nov 10 '09 at 06:00
  • Sorry to be dense, but how do I express and use Satisfies in a generator that produces all the odd elements of list ref? (Haven't gotten the hang of generators yet, I guess ...) ref = [8,10,4,5,7] def is_odd(x): return x % 2 != 0 class Satisfies(object): def __init__(self, pred): self.pred = pred def __eq__(self, test_this): return self.pred(test_this) print ref.index( Satisfies(is_odd)) #>>>3 – behindthefall Nov 11 '09 at 05:22
  • Ouch! That was supposed to be a code snippet! (Does this work?) ref = [8,10,4,5,7] def is_odd(x): return x % 2 != 0 class Satisfies(object): def __init__(self, pred): self.pred = pred def __eq__(self, test_this): return self.pred(test_this) print ref.index( Satisfies(is_odd)) #>>>3 – behindthefall Nov 11 '09 at 05:24
  • BTW, next() is very appealing, but Cygwin and Pydee both are laggards and haven't advanced to 2.6 yet, AFAIK, so .next() will probably keep showing up for a while. – behindthefall Nov 11 '09 at 05:27
  • @behindthefall, give up on putting code in comments -- you've gotta post or edit an existing answer or question (and make sure to whine on the meta site, the more of us explaining this limit on comments is crazy the likelier Joel will ever heed us;-). Anyway, unless you're using s/thing with built-in checks for == like index, `if x=Satisfied(p)` is just a weird way of sayinf `if p(x)`;-). And yeah, even minor-version upgrades always lag (app engine is 2.5 too), but I've written my own easy `def next` for Py<2.6, post a question if you want me to show it! – Alex Martelli Nov 11 '09 at 05:56
6

Not one single function, but you can do it pretty easily in Python 2:

>>> test = lambda c: c == 'x'
>>> data = ['a', 'b', 'c', 'x', 'y', 'z', 'x']
>>> map(test, data).index(True)
3

If you don't want to evaluate the entire list at once you can use itertools, but it's not as pretty:

>>> from itertools import imap, ifilter
>>> from operator import itemgetter
>>> ifilter(itemgetter(1), enumerate(imap(test, data))).next()[0]
3

Just using a generator expression is probably more readable than itertools though.

Note in Python3, map and filter return lazy iterators and you can just use:

>>> from operator import itemgetter
>>> next(filter(itemgetter(1), enumerate(map(test, data))))[0]
3
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Steve Losh
  • 19,642
  • 2
  • 51
  • 44
2

A variation on Alex's answer. This avoids having to type X every time you want to use is_odd or whichever predicate

>>> class X(object):
...     def __init__(self, pred): self.pred = pred
...     def __eq__(self, other): return self.pred(other)
... 
>>> L = [8,10,4,5,7]
>>> is_odd = X(lambda x: x%2 != 0)
>>> L.index(is_odd)
3
>>> less_than_six = X(lambda x: x<6)
>>> L.index(less_than_six)
2
Neuron
  • 5,141
  • 5
  • 38
  • 59
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

Intuitive one-liner solution:

i = list(map(lambda value: value > 0, data)).index(True)

Explanation:

  1. we use map function to create an iterator containing True or False based on if each element in our list pass the condition in the lambda or not.
  2. then we convert the map output to list
  3. then using the index function, we get the index of the first true which is the same index of the first value passing the condition.
wjandrea
  • 28,235
  • 9
  • 60
  • 81
YazanGhafir
  • 464
  • 3
  • 8
  • This is by far the nicest looking approach, but it doesn't early stop once the condition is satisfied – mel Aug 21 '23 at 06:09
0

you could do this with a list-comprehension:

l = [8,10,4,5,7]
filterl = [a for a in l if a % 2 != 0]

Then filterl will return all members of the list fulfilling the expression a % 2 != 0. I would say a more elegant method...

Vincent Osinga
  • 1,043
  • 7
  • 15