Find the index of duplicate elements in list Python | Example code

Using enumerate with for-loop and if statement you can get the index of duplicate elements in python list.

Find an index of duplicate elements in list Python Example

Simple example code.

a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
res = [idx for idx, item in enumerate(a) if item in a[:idx]]
print(res)

Output:

Find the index of duplicate elements in list Python

Another examples using collections

You have to import collections module for this example.

import collections

original = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
dup = [item for item, count in collections.Counter(original).items() if count > 1]
for i in dup:
    print("index of", i, "=", original.index(i))

Output:

index of 1 = 0
index of 2 = 1
index of 5 = 5

How do I get the index of a duplicated string in a list?

Traversing thro the length of the list so that we can keep a track of each index and print the index.

import collections

original = ['A', 'B', 'A', 'B', 'C']
dup = [item for item, count in collections.Counter(original).items() if count > 1]
for i in dup:
    print("index of", i, "=", original.index(i))

Output:

index of A = 0
index of B = 1

Do comment if you have any questions and doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.