How to compare two lists in Python?

6

I have two lists whose content refers to one file1.txt and the other one file2.txt , there are differences in the contents of the files and I want to search < only the data that is in file2.txt and is not in file1.txt , I do not care the other way around.

It is possible to solve this with a loop which compares if element 0 belonging to file2.txt is present in some position in the list of file1.txt, the problem is that it would have to go through all this list.

Is there a easier and simplified way of doing this list match in Python?

    
asked by anonymous 16.02.2016 / 16:19

1 answer

6

I suppose this solves your problem:

lista_final = list(set(lista_arquivo_2) - set(lista_arquivo_1))

Considering that lista_arquivo_1 and lista_arquivo_2 are valid lists in Python.

As mentioned by @BrunoRB, this will not return repeated elements of the list, in case you want to have repeated elements, you can use the following list compression:

lista_final = [x for x in lista_arquivo_2 if x not in lista_arquivo_1]
    
16.02.2016 / 16:24