Compare strings in a list with strings in a list

I see that the code below can check if there is a word

list1 = 'this' compSet = [ 'this','that','thing' ] if any(list1 in s for s in compSet): print(list1) 

Now I want to check if the word is in the list in another list, as shown below:

 list1 = ['this', 'and', 'that' ] compSet = [ 'check','that','thing' ] 

What is the best way to check if there are words in list1 in compSet and do something with nonexistent elements, for example, add 'and' to compSet or remove 'and' from list1?

__________________ update ___________________

I just found that doing the same does not work with sys.path. The code below sometimes works to add the path to sys.path, and sometimes not.

 myPath = '/some/my path/is here' if not any( myPath in s for s in sys.path): sys.path.insert(0, myPath) 

Why is this not working? Also, if I want to perform the same operation on many of my paths,

 myPaths = [ '/some/my path/is here', '/some/my path2/is here' ...] 

How can i do this?

+7
python list
source share
2 answers

There is an easy way to check the intersection of two lists: convert them to a set and use intersection :

 >>> list1 = ['this', 'and', 'that' ] >>> compSet = [ 'check','that','thing' ] >>> set(list1).intersection(compSet) {'that'} 

You can also use bitwise operators:

Intersections:

 >>> set(list1) & set(compSet) {'that'} 

Union:

 >>> set(list1) | set(compSet) {'this', 'and', 'check', 'thing', 'that'} 

You can make any of these results a list using list() .

+8
source share

Try the following:

  >>> l = list(set(list1)-set(compSet)) >>> l ['this', 'and'] 
+1
source share

All Articles