Find the index of the list of fuzzy tuples at the first index of the tuple
I am trying to get the index of a list of 2-tuples in Python where index is 0 of each tuple 'a'
:
list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]
So I'm using the following list comprehension to figure out which index is returned, right?
index_list = [x for x, y in enumerate(list_of_tuples) if x[0] == 'a']
Which gives the following error:
TypeError Traceback (most recent call last)
<ipython-input-22-5d47328b7d9a> in <module>()
----> 1 index_list = [x for x, y in enumerate(list_of_tuples) if x[0] == 'a']
TypeError: 'int' object is not subscriptable
How do I find out the index associated with a list of tuples lookup for the value at the 0th index being equal 'a'
?
source to share
x
- index. You should be able to access the first item y -> y[0]
. y
- every tuple in your list. You can also unpack:
list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]
index_list = [ind for ind, (a, _) in enumerate(list_of_tuples) if a == 'a']
print(index_list)
[0, 1, 2]
If you are print(list(enumerate(list_of_tuples)))
, you can see that the first element is the index and the second is your tuple:
[(0, ('a', 1)), (1, ('a', 2)), (2, ('a', 3))]
So you are trying to index 0 -> 0[0]
with x[0]
.
source to share
First, I recommend that you check your details.
list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]
print list(enumerate(list_of_tuples))
# [(0, ('a', 1)), (1, ('a', 2)), (2, ('a', 3))]
^ ^-----^
x y
Once you understand how to unpack data, it's easy to do.
index_list = [x for x, y in enumerate(list_of_tuples) if y[0] == 'a']
print index_list
source to share