0

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])

S.B
  • 13,077
  • 10
  • 22
  • 49
Jack Lang
  • 11
  • 1
  • This answer your question?: https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list – Carmoreno Jul 26 '21 at 19:11
  • What is the result for `[1, 2, 3, 3, 4, 3, 5, 6,6,6,6]`? – dani herrera Jul 26 '21 at 19:26
  • Does this answer your question? [Index of duplicates items in a python list](https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list) – mkrieger1 Jul 26 '21 at 19:28
  • Does this answer your question? [How to find all occurrences of an element in a list](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – suvayu Jul 26 '21 at 19:28

3 Answers3

1

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]}
S.B
  • 13,077
  • 10
  • 22
  • 49
0

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]
RIAM KIM
  • 21
  • 5
0

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]
Mshane
  • 15
  • 4