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
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.
We can use the in-built python List method, count(), to check if the passed element exists in the List.
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 set
s), 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With