Nips
Nips

Reputation: 13870

Is there better way to check if all entries of a list is in another?

I have something like this:

a = ['a','b','c']
b = ['a','t','g','c','b']

and:

def check_list(a, b):
    for entry in a:
        if entry not in b:
            return False
    return True

How to do this well?

Upvotes: 1

Views: 90

Answers (3)

Omid Raha
Omid Raha

Reputation: 10680

Try this:

a = ['a', 'b', 'c']
b = ['a', 't', 'g', 'c', 'b']

print(all(item in b for item in a))

Output:

True

Upvotes: 0

wim
wim

Reputation: 362766

You can use the set operators:

>>> a = ['a','b','c']
>>> b = ['a','t','g','c','b']
>>> set(a) <= set(b)
True

If you need to handle duplicates aswell:

>>> from collections import Counter
>>> cb = Counter(b)
>>> cb.subtract(Counter(a))
>>> all(count >= 0 for count in cb.values())
True

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

You can use set.issubset:

>>> a = ['a','b','c']
>>> b = ['a','t','g','c','b']
>>> set(a).issubset(b)
True

Upvotes: 2

Related Questions