Chris
Chris

Reputation: 1219

Does list A have any items not in list B

I am trying to figure out how I can return true if my list contains any items not in my blacklist. It might sound strange but I only want to return false if the list is made up entirely of item/s in my blacklist.

Here is what I mean...

blacklist = [one, two, three]

Here is what I would like to happen to the following...

one two three four = true because four is not in the blacklist
one = false because one is in the blacklist
one two three = false because all are in the blacklist
five = true because five is not in the blacklist

Hope that makes sense.

Upvotes: 0

Views: 176

Answers (4)

Timus
Timus

Reputation: 11321

Try something like:

def not_in_blacklist(*args):

    blacklist = ['one', 'two', 'three']

    return any(arg not in blacklist for arg in args)

Results:

print(not_in_blacklist('one', 'two', 'three', 'four')) -> True
print(not_in_blacklist('one'))                         -> False
print(not_in_blacklist('one', 'two', 'three'))         -> False
print(not_in_blacklist('five'))                        -> True

Upvotes: 1

Maxim
Maxim

Reputation: 286

Try something like this:

blacklist = ['one', 'two', 'three'] # these are strings, keep that in mind
lst = [1, 'two', 'three']
new_lst = []
for x in blacklist:
   s = lambda x: True if x not in lst else False
   new_lst.append(s(x))
# Check for overall difference and if it even exists
if any(new_lst):
   print(True)
else:
   print(False)

This returns the single result that you wanted. Either the list has any different items (True) or it has all items same (False)

Upvotes: 0

IamsagarTu
IamsagarTu

Reputation: 88

testList = ['one']
blackList = ['one', 'two', 'three']
result = False
for t in testList:
    if (t not in blackList):
        result = True
        break
    else:
        continue

print(result)

Somethings like this?

Upvotes: 0

Rozxjie
Rozxjie

Reputation: 103

You can find the difference between the 2 lists by subtracting their set():

allowed = list(set(yourlist)-set(blacklist))

This will return a list to see the difference between your list and the blacklist, hence, you can use condition to see if the list is empty or not to return false or true.

Upvotes: 5

Related Questions