Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Ruby's #find_index with lambda?

Tags:

python

list

ruby

In Ruby:

[[1,2],[2,3],[9,3]].find_index {|i| i.include?(3)}

Returns 1, which is the index of the first element in the array containing 3. Is there an equivalent to this in Python? I looked into List's index method, but it doesn't seem to take a lambda as an argument.

like image 469
user886596 Avatar asked Feb 15 '23 06:02

user886596


2 Answers

I typically write something like

>>> a = [[1,2],[2,3],[9,3]]
>>> next(i for i,x in enumerate(a) if 3 in x)
1

If not found, you get a StopIteration exception, or you can pass a default value to return instead as the second argument:

>>> next(i for i,x in enumerate(a) if 99 in x)
Traceback (most recent call last):
  File "<ipython-input-4-5eff54930dd5>", line 1, in <module>
    next(i for i,x in enumerate(a) if 99 in x)
StopIteration

>>> next((i for i,x in enumerate(a) if 99 in x), None)
>>>
like image 84
DSM Avatar answered Feb 17 '23 03:02

DSM


As far as I know, there's no direct equivalent function exist in Python.

You can get multiple indice using list comprehension with enumerate:

>>> [i for i, xs in enumerate([[1,2],[2,3],[9,3]]) if 3 in xs]
[1, 2]

If you need only the first index, you can use next with generator expression:

>>> next(i for i, xs in enumerate([[1,2],[2,3],[9,3]]) if 3 in xs)
1
>>> next((i for i, xs in enumerate([[1,2],[2,3],[9,3]]) if 999 in xs), 'no-such-object')
'no-such-object'
like image 26
falsetru Avatar answered Feb 17 '23 03:02

falsetru