Emil
Emil

Reputation: 1722

Get index of a list with tuples in which the first element of the tuple matches pattern

I have a list of tuples:

    countries = [('Netherlands','31'),
                 ('US','1'),
                 ('Brazil','55'),
                 ('Russia','7')]

Now, I want to find the index of the list, based on the first item in the tuple.

I have tried countries.index('Brazil'), I would like the output to be 2. But instead, that returns a ValueError:

ValueError: 'Brazil' is not in list

I am aware that I could convert this list into a pd DataFrame and then search for a pattern match within the first column. However, I suspect there is a faster way to do this.

Upvotes: 3

Views: 1601

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

You can use enumerate() to find your index:

Try:

idx = next(i for i, (v, *_) in enumerate(countries) if v == "Brazil")
print(idx)

Prints:

2

Upvotes: 4

Related Questions