getting the index of a given component in a list of tuples

Viewed 42

Ok, so I want to get the index of a component in a list of tuples that has a given value. Here's an example of what I have done so far:

import random

tuples=[('a', 1.09), ('b', 5.89), ('c', 6.85), ('d', 9.48)]

x = random.choice(tuples)[0]

Here, Im randomly getting back a,b,c or d(x). Now, I want to find the index of the component that contains x in the "tuples" list.

Hope you see my point!

2 Answers

That should do:

index_of_element = [i for i, t in enumerate(tuples) if t[0] == x][0]

Using enumerate, you iterate through tuples by creating a tuple of for elements and its corresponding index. example: (0, ('a', 1.08))

Then by using if inside the list comprehension, you filter elements by the value of x for the first element t[0] of the current tuple example

This gives you an array with the element that you are looking for. Finally [0] gives you that element.

You might want to check if the list isn't empty in case you don't find it.

You can use a list comprehension with enumerate to identify which index matches the searched value.

indexes = [i for i,v in enumerate(tuples) if v[0] == x]

if the index exists and is unique, you can get the first element: indexes[0]

That said, I don't know what is your use case, but it might be easier to randomly select the index, not the value:

index = random.randint(0, len(tuples))
values = tuples[index][0]
Related