Home python Comparing 2 lists in python

Comparing 2 lists in python




Hello, there are two lists

Ans = ['red', 'blue', 'green', 'white']
  Word = ['red', 'white']

You need to compare the two lists and output the matching elements into a separate list, say, result. There has already been such a question, but I just can’t figure out how to display the same elements.

Answer 1, authority 100%

Still, Python is dynamic and expressive. This cannot be taken away from him.

There are some boolean and arithmetic operators overloaded for sets .

Here is your one-liner:

result = list (set (Ans) & amp; set (Word))

This will give the intersection of both lists:

['red', 'white']

If you want a list of unique elements in the union of two lists:

['red', 'white', 'green', 'blue']
result = list (set (Ans + Word))

Symmetric difference:

['green', 'blue']
result = list (set (Ans) ^ set (Word))

Plain difference (Set from Ans not included in Word ):

['green', 'blue']
result = list (set (Ans) - set (Word))

Option preserving order with fewer type conversions:

sbuf = set (Word)
result = [x for x in Ans if x in sbuf)]

Answer 2, authority 29%

Maybe via a list generator:

Res = [x for x in Ans if x in Word]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions