Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

>>> 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)

like image 266
bandana Avatar asked Nov 09 '09 14:11

bandana


People also ask

How do I get the first index of a list in Python?

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 .

Which function returns the index of first match item from the list?

The index() method returns an integer that represents the index of first match of specified element in the List.

How do you find the index of an element in a list Python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.

What is the index number for the first item in the list Python?

It is important to note that python is a zero indexed based language. All this means is that the first item in the list is at index 0.


1 Answers

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

like image 70
Paul Avatar answered Sep 17 '22 10:09

Paul