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

4

3 Answers 3

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]}
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.