Reputation: 1743
Due to list.index(x)
will only return the index in the list of the first item whose value is x. Is there any way to return every index of same values in the list.
For example, I have a list containing some same values like:
mylist = [(A,8), (A,3), (A,3), (A,3)]
I want to return:
index_of_A_3 = [1, 2, 3]
Upvotes: 3
Views: 17642
Reputation: 2219
It's kinda ugly but:
index_of_A_3 = [i for i in range(len(mylist)) if mylist[i] == (A,3)]
Upvotes: 1
Reputation: 107598
mylist = [(A,8), (A,3), (A,3), (A,3)]
def indices( mylist, value):
return [i for i,x in enumerate(mylist) if x==value]
print indices(mylist, (A,3))
# [1, 2, 3]
Upvotes: 9
Reputation: 10673
Replace (A,3) with what you want or use a lambda.
[i for i in range(len(mylist)) if mylist[i]==(A,3)]
Upvotes: 2