Say I have a list like this:
l = [1, 2, 3, 4, 5, 3]
how do I get the indexes of those 3s that have been repeated?
>Solution :
First you need to figure out which elements are repeated and where. I do it by indexing it in a dictionary.
Then you need to extract all repeated values.
from collections import defaultdict
l = [1, 2, 3, 4, 5, 3]
_indices = defaultdict(list)
for index, item in enumerate(l):
_indices[item].append(index)
for key, value in _indices.items():
if len(value) > 1:
# Do something when them
print(key, value)
Output:
3 [2, 5]
Another would be to filter them out like so:
duplicates_dict = {key: indices for key, indices in _indices.items() if len(indices) > 1}