python – Attempting to compare values ​​from a list in a function does not yield the expected result

Question:

I have a function that receives a list and inside it a loop of repetition with the objective of traversing all the positions and comparing the value of that certain position with the value that comes as a parameter:

def recebeListaVal(number, value):

    lista = number
    valor = value

When the for loop is executed and I try to compare the values ​​that are currently passing through the list with the value received by parameter, it doesn't 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 they were. However, the problem persists, I made the list with repeated occurrences of the number 4 to test for it but it doesn't find it because it doesn't 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)

Answer:

Your function does not enter the for loop since in if you compare the valor variable of type int with the element lista[i] which in the case of the list created by you is a String.

A number with ' around it is read as a String type, so the list

L = ['1','4','3', '4', '5', '6','4']

It only saved the String type values, which can be confirmed as follows:

L = ['1','4','3', '4', '5', '6','4']
for i in L:
    print(type(i))

Return:

<class 'str' <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>

Correction

For the correction you have some options, I believe these are the simplest:

  1. remove the ' when creating the list, looking like this:

    L = [1,4,3, 4, 5, 6,4]

Final code:

def recebeListaVal(number, value):

lista = number
valor = value

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

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

recebeListaVal(L,val)
  1. convert the variable's type to int, using the int() method when doing the comparison (Replace lista[i] with int(lista[i] ):

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

Final code:

def recebeListaVal(number, value):

lista = number
valor = value

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

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

recebeListaVal(L,val)

Hope this helps
-v-

Scroll to Top