Compare two lists in python and return matches

Asked

Viewed 228 times

0

How to compare (old-fashioned) 2 lists in python and return the matches of these two lists

3 answers

9

Convert the lists to ensembles and make the intercession &:

uma_lista = [1, 2, 3, 4,]
outra_lista = [3, 4, 5, 6,]


print(set(uma_lista) & set(outra_lista))

resulting:

{3, 4}

Test the code on Repl.it

  • 1

    Great answer! Not only because it’s simpler to see (and understand) what’s going on, but because I also have the impression that sets tend to be more performatic with large amounts of items. However, I did not take the test to confirm this hypothesis.

  • 2

    @Luizfelipe With large lists the difference is brutal: https://ideone.com/xnywb5 - with small lists, not so much (and do not use set is even a little faster): https://ideone.com/CLrWSe

  • 2

    Thanks for testing, @hkotsubo! Really, it makes sense to take a little longer for smaller lists because of the cost of creating the set, correct? But in this type of case (smaller), as the difference is so derisory, I would tend to lose this very little performance in favor of greater readability, which is also an important factor. :-)

  • 1

    I knew there was a difference in performance, but I had no idea it was such a difference.

  • 2

    @Luizfelipe Yes, it has the cost of creating the set's, but which in my opinion is paid (not only in time, but in the question of semantics/readability that you mentioned). Remembering that a set does not guarantee the order of the elements, so if the order is important, then you have to use the same lists...

  • 1

    If you need a set ordained has here together with other orderly collections.

Show 1 more comment

7


The simplest way is by using a comprehensilist on.

uma_lista = [1, 2, 3, 4,]
outra_lista = [3, 4, 5, 6,]

iguais = [elemento for elemento in uma_lista if elemento in outra_lista]

This command will create a new list by iterating the elements of uma_lista but just adding those that are within outra_lista.

And the result will be the list iguais only with the same elements.

[3, 4]

2

Another example with strings could be done this way:

If you would like to subtract the same elements:

uma_lista = ['oi', 'bem', 'certo']
outra_lista = ['oi', 'belo', 'jeito']
iguais = [elemento for elemento in uma_lista if elemento in outra_lista]
print(iguais)

Resultado ['oi']

If you would like to return only the intersection of all letters contained in the lists:

lista1 = []
lista2 = []
uma_lista = ['oi', 'bem', 'certo']
outra_lista = ['oi', 'belo', 'jeito']
for pos, palavras in enumerate(uma_lista):
    lista1 += palavras
for pos, palavras in enumerate(outra_lista):
    lista2 += palavras
lista1 = set(lista1)
lista2 = set(lista2)
print(lista1-lista2)

Resultado: {'b', 't', 'e', 'i', 'o'}

Browser other questions tagged

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