user3578925
user3578925

Reputation: 931

Find index of a tuple in a list of tuples

I have a list of tuples and I want to find the index of a tuple if the tuple contains a variable. Here is a simple code of what I have so far:

items = [('show_scllo1', '100'), ('show_scllo2', '200')]
s = 'show_scllo1'
indx = items.index([tupl for tupl in items if tupl[0] == s])
print(indx)

However I am getting the error:

indx = items.index([tupl for tupl in items if tupl[0] == s])
ValueError: list.index(x): x not in list

What I am doing wrong?

Upvotes: 5

Views: 15581

Answers (4)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

It seems as though you want the value, so you're asking for the index.

You can search the list for the next matching value, using next:

>>> items = [('show_scllo1', '100'), ('show_scllo2', '200')]

>>> next(number for (name, number) in items
...      if name == 'show_scllo1')
'100'

So you don't really need the index at all.

Upvotes: 2

donkopotamus
donkopotamus

Reputation: 23176

The following will return you the indices of the tuples whose first item is s

indices = [i for i, tupl in enumerate(items) if tupl[0] == s]

Upvotes: 5

Joran Beasley
Joran Beasley

Reputation: 113948

index = next((i for i,v in enumerate(my_tuple_of_tuple) if v[0] == s),-1)

Is how you should probably do that

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

You are checking for the presence of a list in items, which doesn't contain a list. Instead, you should create a list of each index where the item of interest is found:

indx = [items.index(tupl) for tupl in items if tupl[0] == s]

Upvotes: 1

Related Questions