2

Does anyone know how I can get the last index position of duplicate items in a python list containing duplicate and non-duplicate items? I have a list sorted in ascending order with [1, 1, 1, 2, 2, 3, 3, 4, 5] I want it to print the last index of duplicate items and index on non-duplicate items like this

2
4
6
7
8

I tried doing this way but could only print the starting index of duplicate elements and misssed non-duplicate items.

id_list = [1, 1, 1, 2, 2, 3, 3, 4, 5]
for i in range(len(id_list)):
    for j in range(i+1,len(id_list)):
        if id_list[i]==id_list[j]:
            print(i)
Ragesh_
  • 93
  • 1
  • 7

3 Answers3

4

Loop on the list using enumerate to get indexes & values, and use a dictionary and retain the last index (last index "wins" when there are duplicates). In the end, sort the indexes (as dictionaries aren't ordered, but you can use an OrderedDict):

import collections

lst = [1, 1, 1, 2, 2, 3, 3, 4, 5]
d = collections.OrderedDict()

for i,v in enumerate(lst):
    d[v] = i

print(list(d.values()))

prints:

[2, 4, 6, 7, 8]

The advantage of this solution is that it works even if the duplicates aren't consecutive.

Python 3.7 guarantees the order of the base dictionaries so a simple dict comprehension solves it:

{v:i for i,v in enumerate(lst)}.values()
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    Or just `{x:i for i,x in enumerate(lst)}`, particularly in newer version of Python where `dict` retains insertion order. – tobias_k Dec 10 '18 at 22:42
4

You can use enumerate and check the next index in the list. If an element is not equal to the element in the next index, it is the last duplicate:

lst = [1, 1, 1, 2, 2, 3, 3, 4, 5]
result = [i for i, x in enumerate(lst) if i == len(lst) - 1 or x != lst[i + 1]]

print(result)
# [2, 4, 6, 7, 8]
slider
  • 12,810
  • 1
  • 26
  • 42
0

You can use a list comprehension with enumerate and zip. The last value will always be in scope, so we can include this at the end explicitly.

L = [1, 1, 1, 2, 2, 3, 3, 4, 5]

res = [idx for idx, (i, j) in enumerate(zip(L, L[1:])) if i != j] + [len(L) - 1]

print(res)

# [2, 4, 6, 7, 8]
jpp
  • 159,742
  • 34
  • 281
  • 339