-1

I have this list: [1, 2, 3, 6, 1, 3]

I'm trying to get the indexes of the list elements that are duplicates. In this case, the code should return 0, 4, because there are duplicate elements at the 0th and 4th indexes. However, when I run my code, my output only shows 4, for the 4th index, and does not print out the 0th index as well. Can anyone help me find the problem in the code?

lst = [1, 2, 3, 6, 1, 3]

oc_set = set()
res = []
for idx, val in enumerate(lst):
    if val not in oc_set:
        oc_set.add(val)         
    else:
        res.append(idx)     

print(res)

Output:

[4] [4]

Alex S.
  • 1
  • 2
  • Does this [answer](https://stackoverflow.com/a/68157071) help at all? – quamrana Aug 17 '22 at 07:01
  • After the first duplicate you don't remove the first from oc_set. After appending the second 1, the 3 is in 4th index again and added to res as well. You only put in the duplicate and not the "original" value – flzzz Aug 17 '22 at 07:03
  • This code will find indexes of the duplicated elements, but not the index of the first occurrence of the element. – Yuri Ginsburg Aug 17 '22 at 07:10
  • Why are the indices of the two 3's not supposed to be included in the output? – blhsing Aug 17 '22 at 07:35

1 Answers1

0

What the code is doing is giving you the indexes of repeated value, since in the array res is storing the repeated indexes only. to print the index of repeated values you can use below code.

lst = [1, 2, 3, 6, 1, 3]

oc_set = set()
res = []
for idx, val in enumerate(lst):
    if val not in oc_set:
        oc_set.add(val)         
    else:
        res.append(val)     

print(res)

ans = []
for idx, val in enumerate(lst):
    if val in res:
        ans.append(idx)
print(ans)
chirrumishra
  • 53
  • 1
  • 6