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:
If you want a list of unique elements in the union of two lists:
['red', 'white', 'green', 'blue'] result = list (set (Ans + Word))
['green', 'blue'] result = list (set (Ans) ^ set (Word))
Plain difference (Set from
Ans not included in
['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]