Skip to content

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

  • by

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 example using collections

You have to import the 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 through 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 or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading