Get from a list all indices whose element is equal to a certain value

Asked

Viewed 79 times

-1

This is my code:

def procuras(lista,valor):
    dicionario = {}
    for valor in lista:
        if valor in dicionario:
            dicionario[valor] = [i for i, item in enumerate(lista) if item == valor]
        else:
            dicionario[valor] = lista.index(valor)
    return (dicionario[valor])

Runs this way:

 procuras([5,2,5,4,5,2,3,5], 5)

The result is always 8 even if I try to see another value. I needed to get:

procuras([1,2,1,4,5,2,3,1], 2)

[1, 5] - or is all the indexes where it appears.

If it doesn’t exist you should just give it to me: []

1 answer

4


You don’t need to create a dictionary to save the indexes. Just go through the list with enumerate, that you can get the index and its element at the same time:

def procuras(lista, valor):
    indices = []
    for indice, elemento in enumerate(lista):
        if valor == elemento:
            indices.append(indice)
    return indices

So each time the value is found in the list, I add the respective index to the list of indices. If the value is not found once, the returned list is empty. Testing:

print(procuras([1, 2, 1, 4, 5, 2, 3, 1], 2)) # [1, 5]
print(procuras([5, 2, 5, 4, 5, 2, 3, 5], 5)) # [0, 2, 4, 7]
print(procuras([1, 2, 3], 5)) # []

You can also use the syntax of comprehensilist on, much more succinct and pythonic.

def procuras(lista, valor):
    return [ indice for indice, elemento in enumerate(lista) if valor == elemento ]

The result is the same as the previous code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.