7

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

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

Now I want to check if a word in a list is in some other list as below:

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

What's the best way to check if words in list1 are in compSet, and doing something over non-existing elements, e.g., appending 'and' to compSet or deleting 'and' from list1?

__________________update___________________

I just found that doing the same thing is not working 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 do the same operation on a set of my paths,

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

How can I do it?

3
  • Re your update, what is not working? Is it giving an error? Perhaps you are just not using backslashes in your myPath variable? Commented Sep 28, 2016 at 21:00
  • @brianpck Thanks, I updated. The function above to add a path to sys.path works inconsistently. It works sometimes and sometimes not. Maybe it is a specific problem of my environment, I guess... By the way, If I do this adding to path thing over a list of paths with sys.path, is Intersection function is the best to do it? Commented Sep 28, 2016 at 22:16
  • If you want to find the paths that are in both lists, then yes, intersection is the best way. With regard to sys.path, I recommend asking another question if this is an issue since it's really a separate issue. Commented Sep 28, 2016 at 23:45

2 Answers 2

8

There is a simple way to check for 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:

Intersection:

>>> 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().

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!
Hi Brian, I just updated my question. Can you please look into it?
1

Try that:

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

1 Comment

Just to clarify; this is showing the words in list1 that is not in compSet, and not which words that is in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.