Jack Lang
Jack Lang

Reputation: 11

How do I find each duplicate's index in a List in Python?

For example, let's say I have a list:

lst = [1, 2, 3, 3, 4, 3, 5, 6]

Is there any function that returns all the indexes of the 3s?(which would return [2, 3, 5])

Upvotes: 0

Views: 1834

Answers (3)

Mshane
Mshane

Reputation: 15

I was trying to figure out a solution for a similar problem and this is what I came up with.

def locate_index(item_name, list_name):
    """Determine the indexes of an item if in a list."""
    locations = []
    for i in range(len(list_name)):
        if list_name[i] == item_name:
            locations.append(list_name.index(item_name, i, len(list_name)))
    print(locations)

Example:

lst = [1, 2, 3, 3, 4, 3, 5, 6]
list2 = [1, 2, 3, 3, 4, 3, 5, 6, 6, 6, 6]

locate_index(3, lst)     ---- a)
locate_index(6, list2)   ---- b)

Output

a)
[2, 3, 5]

b)
[7, 8, 9, 10]

Upvotes: 0

RIAM KIM
RIAM KIM

Reputation: 21

You can simply use function enumerate(lst) it returns elements index_number and value. for example

lst[0] = 1

the case above index_number is 0 and value is 1

so you can just use enumerate function for returning index number using if condition (returns it when the value is 3)

lst = [1, 2, 3, 3, 4, 3, 5, 6]
lst_result = [i for i, v in enumerate(lst) if v == 3]
print(lst_result)

your outcome will be

[2,3,5]

Upvotes: 0

S.B
S.B

Reputation: 16486

I've changed the list in order to build a dictionary of all items that appeared more than once.

from collections import Counter

lst = [1, 2, 3, 3, 4, 3, 5, 2, 6]

# only values that appears more than once
c = Counter(lst) - Counter(set(lst))

res = {}
for i, elem in enumerate(lst):
    if elem in c:
        item = res.get(elem)
        if item:
            item.append(i)
        else:
            res[elem] = [i]

print(res)

output :

{2: [1, 7], 3: [2, 3, 5]}

A better approach is to use defaultdict :

from collections import defaultdict

lst = [1, 2, 3, 3, 4, 3, 5, 2, 6]

d = defaultdict(list)
for i, elem in enumerate(lst):
    d[elem].append(i)

print({k: v for k, v in d.items() if len(v) > 1})

output :

{2: [1, 7], 3: [2, 3, 5]}

Upvotes: 1

Related Questions