ami91
ami91

Reputation: 1354

Is there a way to find index of "in" keyword match in python

The title of this post is probably pretty vague. Here is what I need to know

If I use something like

if x in list

how do I find the index in the list where a match occurs?

Upvotes: 1

Views: 1895

Answers (2)

wim
wim

Reputation: 363304

You can't.

It's better to use list_.index(x) for this use case.

If there's a match in your sequence zero or multiple times, you should prefer to use enumerate:

>>> list_ = ['foo', 'bar', 'spam', 'foo', 'eggs']
>>> idxs = [i for i,x in enumerate(list_) if x == 'foo']
>>> print idxs
[0, 3]

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251548

You can't get that from in itself. For lists, you can use the index method:

>>> [1, 2, 5, 8, -1, 2].index(2)
1

This will raise an exception if the item is not in the list. Note that it returns the index of the first occurrence. It might occur multiple times.

Upvotes: 7

Related Questions