Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if one list contains another? [duplicate]

Tags:

python

list

Is there a built-in Pythonic way to determine if one list completely contains the contents of another, including duplicated entries but disregarding the order of items?

>>> l1 = [2, 2, 3]
>>> l2 = [2, 2]
>>> l3 = [3, 2]
>>> l4 = [2, 2, 2]
>>> l5 = [2, 5, 2]

>>> is_superset(l1, l2)
True
>>> is_superset(l1, l3)
True
>>> is_superset(l1, l4)
False
>>> is_superset(l1, l5)
False
like image 665
Chuck Avatar asked May 04 '18 17:05

Chuck


People also ask

How do you check if a list contains items from another list?

To check if a list contains any elements of another list: Use a generator expression to iterate over the list. Check if any elements in the first list are contained in the second list. The any() method will return True if the list contains any elements of the other list.

How do you check if elements of a list is present in another list in Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List.


1 Answers

If there were no duplicates, or duplicates didn't matter (that is, if your l1 and l3 were both supersets of each other), you'd just use sets. But since if you want l1 to be a proper superset of l3, you're talking about multisets. Fortunately, Counter already implements multisets for you:

from collections import Counter
def is_superset(a, b):
    return not Counter(b) - Counter(a)

Notice that this - is proper multiset difference between multisets (just as - is proper set difference between sets), not an elementwise subtraction across dicts. So if you subtract a super(multi)set, you get an empty multiset (that is, Counter()—which is, like all empty collections in Python, falsey).

So now:

>>> is_superset(l1, l2)
True
>>> is_superset(l1, l3)
True
>>> is_superset(l1, l4)
False
>>> is_superset(l1, l5)
False

Plus:

>>> is_superset(l3, l1)
False
like image 84
abarnert Avatar answered Oct 05 '22 11:10

abarnert