Protocole
Protocole

Reputation: 1743

Indexing of Same Values in a List

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

Answers (4)

Stephane Reyes
Stephane Reyes

Reputation: 49

more quickly !!!!

index_of_A_3= np.where(mylist == (A,3))[0]

Upvotes: 0

David Miller
David Miller

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

Jochen Ritzel
Jochen Ritzel

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

Kabie
Kabie

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

Related Questions