Python | Duplicate element indices in list

While working with Python list, sometimes, we require to check for duplicates and may also sometimes require to track their indices. This kind of application can occur in day-day programming. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using loop + set()
This task can be solved using the combination of above functions. In this, we just insert all the elements in set and then compare each element’s existence in actual list. If it’s the second occurrence or more, then index is added in result list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Duplicate element indices in list
# Using set() + loop
  
# initializing list
test_list = [1, 4, 5, 5, 5, 9, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Duplicate element indices in list
# Using set() + loop
oc_set = set()
res = []
for idx, val in enumerate(test_list):
    if val not in oc_set:
        oc_set.add(val)         
    else:
        res.append(idx)     
          
# printing result
print("The list of duplicate elements is :  " + str(res))

chevron_right


Output :



The original list is : [1, 4, 5, 5, 5, 9, 1]
The list of duplicate elements is :  [3, 4, 6]

 

Method #2 : Using list comprehension + list slicing
This method is one liner alternative to perform this task. In this we just check for the non repeating element using list slicing and keep adding index in case it’s repeated.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Duplicate element indices in list
# Using list comprehension + list slicing
  
# initializing list
test_list = [1, 4, 5, 5, 5, 9, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Duplicate element indices in list
# Using list comprehension + list slicing
res = [idx for idx, val in enumerate(test_list) if val in test_list[:idx]]
          
# printing result
print("The list of duplicate elements is :  " + str(res))

chevron_right


Output :

The original list is : [1, 4, 5, 5, 5, 9, 1]
The list of duplicate elements is :  [3, 4, 6]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.