In Python, how can I find the index of the first item in a list that is NOT some value?
Posted
by Ryan B. Lynch
on Stack Overflow
See other posts from Stack Overflow
or by Ryan B. Lynch
Published on 2010-04-30T23:35:07Z
Indexed on
2010/04/30
23:37 UTC
Read the original article
Hit count: 288
Python's list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x.
Basically, I need to invert the index(x) method. I need to get the index of the first value in a list that does NOT have the value x. I would probably be able to even just use a function that returns the index of the first item with a value != None.
I can think of a 'for' loop implementation with an incrementing counter variable, but I feel like I'm missing something. Is there an existing method, or a one-line Python construction that can handle this?
In my program, the situation comes up when I'm handling lists returned from complex regex matches. All but one item in each list have a value of None. If I just needed the matched string, I could use a list comprehension like '[x for x in [my_list] if x is not None]', but I need the index in order to figure out which capture group in my regex actually caused the match.
© Stack Overflow or respective owner