Attempt to compare values from a list in a function does not generate the expected result

Asked

Viewed 54 times

3

I have a function that receives a list and inside it a loop of repetition in order to go through all the positions and compare the value of that particular position with the value that comes by parameter:

def recebeListaVal(number, value):

    lista = number
    valor = value

When the noose for is executed and I try to compare the values that are currently going through the list with the value received by parameter, does not enter the condition.

for i in range(len(lista)):    
    if valor == lista[i]:      
        print(f'{value} elemento encontrado na lista contendo: {lista[i]}')

I tried to perform a "manual debug" using print before the if to find out if the values are assigned and I found that yes. However, the problem persists, I made the list with repeated occurrences of the number 4 to test to find it but not because it does not enter the condition. Below are the entries for the function and its call:

L = ['1','4','3', '4', '5', '6','4']
val = int(input('Digite um valor para buscar na lista : '))

recebeListaVal(L,val)
  • 3

    The problem is that you are comparing a number (returned by conversion via int) with a string (each element in your list is a string). Either convert all list elements to string or compare them to a string. Also, allow me to question the necessity of this: lista = number; valor = value. Another thing is you don’t need to wear one range there. As lists are iterable in Python, you can already traverse directly through the elements, like this for element in list: .... :)

  • In this case Luiz Felipe, is there no need for list and value assignments? I will try to improve the code and pay attention to this issue of int and str conversion, I will come back here to give a feedback, vlw!

  • 1

    Note the difference from this list: L = ['1','4','3', '4', '5', '6','4'] for this: L = [1, 4, 3, 4, 5, 6, 4] - In the input you use int , as @Luizfelipe said. The comparison expects a list of numbers. If for some reason you can’t touch the list (if it comes from an origin you can’t control) you can do this too: if valor == int(lista[i]): effectively converting each item into int.

  • @Bacco and @Luiz Felipe, with the conversion everything was solved, now is entering the if and I can count how many times the value has been found! Gratitude!

No answers

Browser other questions tagged

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