Possible Duplicate:
Python: How to find list intersection?
I have two lists of data in a .txt
data1 = "name1", "name2", "name3", "name4" etc.
data2 = "name3", "name6", "name10" etc.
I want to find out which names appears in both list How would I do it?
To compare two lists and return matches with Python, we can use the set's intersection method. We have 2 lists a and b that we want to get the intersection between. To do this, we convert a to a set with set . Then we call intersection with b and assign the intersection of a and b to intersection`.
The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.
Method 2:Using Set's intersection property Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With