How to compare two lists in Python?

Asked

Viewed 16,188 times

8

I have two lists whose contents refer to a arquivo1.txt and the other one arquivo2.txt, there are differences in the contents of the files and wish to search only the data that is in file2.txt and is not in file1.txt, I don’t care the other way around.

It is possible to solve this with a loop which compares if the element 0 belonging to the arquivo2.txt is present in some position of the archive1.txt list, the problem is that you would have to go through that whole list.

There’s a way easier and simplified to make this match of lists in Python?

2 answers

10


I imagine that solves your problem:

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

whereas lista_arquivo_1 and lista_arquivo_2 are valid Python lists.

As @Brunorb mentioned, this will not return repeated elements from the list, if 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]
  • 1

    Note only that duplicates will be removed, for example if you have two elements "hi" in lista_arquivo_2 (and there is a "hi" in lista_arquivo_1) the final result will contain only one "hi" instead of two and the order will also not be preserved.

  • Note that the situation that "keeps the elements repeated" implicitly includes the loop that traverses the entire list_arquivo_1 for each item in list_arquivo_2 - the algorithm is O(N²). The great advantage of the example with sets is that it searches in sets (set) in Python are made in constant time.

-1

Maybe if you use the expression:

list(filter(lambda x: x in lista1, lista2))

Browser other questions tagged

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