Search code examples
python-3.xlistindexingtuplesvalueerror

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.


Solution

  • 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