Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List indexes of duplicate values in a list with Python

I am trying to modify this definition that lists duplicate items so that it lists indexes of duplicate values. Also, I would like it to list ALL of the duplicates that means the resultant for a = [1,2,3,2,1,5,6,5,5,5] would be duplicate_indexes = [3,4,7,8,9] Here's the definition:

def list_duplicates(seq):
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    seen_twice = set( x for x in seq if x in seen or seen_add(x) )
    # turn the set into a list (as requested)
    return list( seen_twice )

a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
like image 970
konrad Avatar asked May 14 '14 04:05

konrad


People also ask

How do I get the index of duplicate items in a list?

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

How do you get all the index of an element in a list in Python?

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.


2 Answers

List comprehension to print the index of duplicates. It slices the list till the selected index and return the index value if the item is already present in the sliced list

a= [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
result=[idx for idx, item in enumerate(a) if item in a[:idx]]
print result #[3, 4, 7, 8, 9]
like image 141
Karthik Avatar answered Oct 22 '22 02:10

Karthik


def list_duplicates(seq):
    d = {}
    for i in seq:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    dups = []
    for i in d:
        if d[i] > 1:
            dups.append(i)
    lst = []
    for i in dups:
        l = []
        for index in range(len(seq)):
            if seq[index] == i:
                l.append(index)
        lst.append(l[1:])
    new = []
    for i in lst:
        for index in i:
            new.append(index)   
    return new
like image 26
user3552506 Avatar answered Oct 22 '22 02:10

user3552506