# Get all the indices of the same element

1

I have two lists `listA = [0, 4, 1, 3, 2]` and `listB = [0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]` what I want is to get all those indexes where the element of `listA` appears in `listB` or that as a result would have `listR = [0, 1, 10, 11, 12, 13, 2, 3, 7, 8, 9, 4, 5, 6]` and try doing with a `for` but obviously it takes a long time.

asked by Luis Miguel 07.12.2018 в 00:03
source

2

An efficient method can be to build before a dictionary in which the keys are the numbers observed in B, and the values are lists with the indexes within B in which they appear.

This dictionary is easy to build:

``````from collections import defaultdict

listB = [0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
dic = defaultdict(list)
for indice, elemento in enumerate(listB):
dic[elemento].append(indice)
``````

When this loop ends, `dic` contains the following dictionary:

``````{0: [0, 1],
1: [2, 3],
2: [4, 5, 6],
3: [7, 8, 9],
4: [10, 11, 12]}
``````

where you see, for example, that the data `3` appeared in indexes `[7,8,9]` .

From this dictionary it is easy to build the list that you ask, simply by going through A and adding to the result list the lists that come out of the dictionary, according to the value of the element of A:

``````listA = [0, 4, 1, 3, 2]
r = []
for elemento in listA:
r.extend(dic[elemento])
``````

When finished, `r` has the list you were looking for:

``````[0, 1, 10, 11, 12, 2, 3, 7, 8, 9, 4, 5, 6]
``````

Note that if any data that was not in B appears when traversing A, line `dic[elemento]` will cause an error because there is no such key in the dictionary. You can easily fix it if instead of `dic[elemento]` you put `dic.get(elemento, [-1])` , for example, so you can `-1` for cases where you can not find it (or `[None]` , or the value you want to put)