Compare two lists element by element:

Asked

Viewed 38 times

-5

Hi I’m trying to develop a code, the code is:

lista1 = ['5','5','1','4']
lista2 = ['5','5','0','1']

I was trying to get him to compare every element of Lista2 to list 1 and then identify element by element. In the list 2 if the element is equal and in the correct Indice of the list 1, if the element is equal and in the wrong Indice, if the element is wrong. The output would be more or less:

>>indice 0: elemento da lista 2 é igual ao da lista 1
>>indice 1: elemento da lista 2 é igual ao da lista 1
>>indice 2: elemento da lista 2 não é igual ao da lista 1
>>indice 3: elemento da lista 2 é igual ao da lista 1 mas está no indice errado

I tried to use for, and in an if using if Lista2[2] in lista1, but I couldn’t solve it the way I wanted.

1 answer

1


How would you do it manually? That is, you would compare the list item by item. If the item of the same index of the first list is equal to the one of the second you notify that they are equal, otherwise you check whether it exists in the other list or, otherwise, the value does not exist in the other list.

A simple solution to implement would be using the function zip() to combine the elements of the list, thus...

lista_1 = ['5','5','1','4']
lista_2 = ['5','5','0','1']

for index,data in enumerate(zip(lista_1,lista_2)):
    i, j = data
    print(f"Índice {index}: ", end="")
    if i == j:
        print("Valores são iguais.")
    elif j in lista_1:
        print("Valores iguais mas em índice diferente.")
    else:
        print("Valores diferentes.")

And the result:

Índice 0: Valores são iguais.
Índice 1: Valores são iguais.
Índice 2: Valores diferentes.
Índice 3: Valores iguais mas em índice diferente.

The use of the function enumerate() is to generate the sequential number for the indices.

Browser other questions tagged

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