How to find matching items from two lists?

Possible duplicate:
Python: how to find the intersection of a list?

I have two data lists in .txt

data1 = "name1", "name2", "name3", "name4" etc. data2 = "name3", "name6", "name10" etc. 

I want to know which names appear on both lists. How do I do this?

+6
source share
4 answers

Use sets :

 set(data1) & set(data2) 

The & operator means "give me the intersection of these two sets"; alternatively you can use the .intersection method:

 set(data1).intersection(data2) 
+26
source
 nf = [x for x in data1 if x in data2] nf 

will return a common item in both lists

+4
source
 >>> [ name for name in data1 if name in data2 ] ['name3'] 
0
source
 For a in data1: for b in data2: if a==b: print(a) 

This is one way to do this, not the best way though

-2
source

Source: https://habr.com/ru/post/921137/


All Articles