Home > Software design >  How to get the indexes of the same values in a list?
How to get the indexes of the same values in a list?

Time:12-27

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?

CodePudding user response:

This should do it

list = [1,2,3,4,5,3]
deletes = 0;
for element in list:
   if element == 3:
       print(list.index(element)   deletes)
       deletes =  1;
       list.remove(3)


Outputs:

2
5

CodePudding user response:

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]
  • Related