how to find the indexes of an item that repeats in a list in Python

Asked

Viewed 166 times

1

have a list l = [1,6,6,2,3,6] and I want to form another with all the indexes of the element 6. In this case, the second list should be l2 = [1,2,5], however, when I try to use the l.index(6), output is only the first index.

Entree:

l = [1,6,6,2,3,6]
l2 = []
a = l.index(6)
l2.append(a)
print(l2)

Exit

[1]

3 answers

1

To resolve this issue you will need to implement a repeat loop and scroll through such list with the help of enumerate function().

Following this logic we can implement the following code:

l = [1, 6, 6, 2, 3, 6]
l2 = list()
for indice, item in enumerate(l):
    if item == 6:
        l2.append(indice)

print(l2)

Note that when we execute this code the loop for will go through the entire list l and with the help of the enumerate verify the indexes of their elements. And, if the said element has value 6, its index will be added to the list L2. And then the list L2 will be shown.

The exit will be:

[1, 2, 5]

Another interesting way to resolve this issue is to use List Comprehensio. In this case the code could be left with only 1 code line. The code would be:

print([indice for indice, item in enumerate([1, 6, 6, 2, 3, 6]) if item == 6])

1

You can create a list directly using list comprehension:

l = [1,6,6,2,3,6]
l2 = [ i for i in range(len(l)) if l[i] == 6 ]

We check by index if the 6 is contained, if you add the index to the list. In this case there is no need to use the enumerate.

Your exit will be:

[1, 2, 5]

1

An alternative is to build a dictionary that stores in the keys the distinct items of the input list and in the values a list with occurrence indexes of their respective keys in the input list and then search for an item.

The algorithm uses two functions:

  1. indexar_correncias(t) accepted as a parameter t, one tuple:

    • Creates an empty dictionary resultado.
    • Creates a enumeration about t and for each element e in that enumeration:
      • Check if there is a key e[1] in resultado:
        • If any, the value of the key e[1] is attached e[0].
        • If it does not exist, it is created in resultado the key e[1] and its value is a list containing e[0].
      • The resultado.
  2. ocorrencias(s , item) accepted as a parameter s, one sequence, and item a whole:

    • Converts the sequence s in a tuple and passes it as an argument to function indexar_correncias() that returns in o the dictionary whose values are lists with occurrence indices of their respective keys in s.
    • Checks whether in o there is the key item:
      • If it exists returns the value o[item] which is a list of the indications of the apparitions of item in s.
      • If it does not exist returns an empty list.

Example:

from functools import lru_cache 
#from random import chooices                          #<-- Descomente a linha caso faça o teste a seguir.

l = [1,6,6,2,3,6]
#l = [c for c in choices(range(1, 100), k=1000000)]   #<-- Teste também o algoritmo com uma entrada mais robusta.


@lru_cache(maxsize=None)                      #Informa que a função será cacheada
def indexar_correncias(t):
    resultado = {}                            #Cria um dicionário vazio
    #Para cada elemento e em enumerate(t)...
    for e in enumerate(t):
        #Verifica se existe a chave e[1] em resultado...
        if e[1] in resultado:
            resultado[e[1]].append(e[0])      #Se existir, ao valor da chave e[1] é apensado e[0].
        else:
           resultado[e[1]] = [e[0]]           #Se não existir, é criada em resultado a chave e[1].
    return resultado                          #Retorna o resultado.
    
def ocorrencias(s , item):
    o = indexar_correncias(tuple(s))          #retorna em o o dicionário cujos os valores são listas com índices de ocorrência de suas respectivas chaves em s.
    #Verifica se em o existe a chave item
    if item in o:
        return o[item]                        #Caso exista retorna o valor o[item].
    return []                                 #Retorna uma lista vazia.
    
while True:
    s = input("Digite um numero para buscar os seus indices: ")
    if s.isnumeric():
        print(ocorrencias( l, int(s)))
    elif s == "":
        break

Test in ideone.

The line @lru_cache(maxsize=None) is a decorator to wrap a function in a fireproof memoisable that is, once a function is executed with a given argument, a cache is created in stored memory of the function result for that argument and then each time the function is called with that same argument instead of redoing all the operation and iterations by the argument it caches the result.
For small entries this feature is irrelevant but for bulky data entries it is an essential resource. In the first function call with an unamended argument to time complexity of function is O(n), after first call to an argument the time complexity of the function is O(1).

indexar_correncias() is fed with tuple as one of the requirements for the lru_cache() function is that the parameters of the memoised function are hasheable and in python only immutable objects are hashable and tuples are immutable sequences.

Browser other questions tagged

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