Search code examples
pythonlistcontains

A list contains another list with repetition


I need to check if a list contains every element of another list in python. Not the set operation exactly, because in set distinct values are considered. How can I do it?

Sample: a is the larger list, b is the smaller set

a = [1, 1, 2, 4], b = [1, 2, 3] -> False
a = [1, 1, 2, 3], b = [1, 2, 3] -> True
a = [1, 2, 4], b = [1, 2, 1] -> False // Because b has two 1s but a has only one.

I would like to request you to look at the third case carefully.

[N. B.] I know exactly how it can be done through hash map. But I want something less bulky.


Solution

  • A simple one-liner with Counter

    def isin(a, b): return not (Counter(b) - Counter(a))
    

    Demo:

    >>> isin([1, 1, 2, 4], [1, 2, 3])
    False
    >>> isin([1, 1, 2, 3], [1, 2, 3])
    True
    >>> isin([1, 1, 2, 4], [1, 2, 1])
    True
    >>> isin([1, 2, 4], [1, 2, 1])
    False