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.
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)
>>>
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With