Find index of a tuple in a list of tuples
13,021
Solution 1
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.
Solution 2
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]
Solution 3
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]
Solution 4
index = next((i for i,v in enumerate(my_tuple_of_tuple) if v[0] == s),-1)
Is how you should probably do that
Author by
user3578925
Updated on June 24, 2022Comments
-
user3578925 almost 2 years
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?