How can I determine if one list contains another in Python? [duplicate]

  • A+
Category:Languages

This question already has an answer here:

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 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: